C++ 如何在CPP中访问模板结构常量变量
我正在使用一个代码,其中我将一个常量变量传递给模板结构,如下所示C++ 如何在CPP中访问模板结构常量变量,c++,templates,C++,Templates,我正在使用一个代码,其中我将一个常量变量传递给模板结构,如下所示 #include <iostream> using namespace std; //Compiler version g++ 6.3.0 template<typename T> struct Data { T age; }; void show(); int main() { Data<const int> person{ 18
#include <iostream>
using namespace std;
//Compiler version g++ 6.3.0
template<typename T>
struct Data {
T age;
};
void show();
int main()
{
Data<const int> person{
18
};
cout << person.age;
show();
}
void show(){
}
#包括
使用名称空间std;
//编译器版本g++6.3.0
模板
结构数据{
T年龄;
};
void show();
int main()
{
数据员{
18
};
cout您的代码根本不起作用。person
变量没有填充到show()
的主体中,因此在该函数中,您只需创建一个默认结构,在其中不指定值。最后,它崩溃了
您可以做的是:
将结构传递给函数并获取其内部变量
在全局空间中创建一个静态结构,并在函数中读取它
使用lambdas
您可以将person
声明为全局变量…但我强烈反对使用全局变量。或者您可以在main()
中定义show()
,作为lambda函数,捕获person
;例如auto show=[&]{std::cout我的建议是通过一个引用传递给一个人来显示。或者让show成为Data@Max66我真的很抱歉,兄弟,在我的代码中,我不能使用lambda,我只想从用户定义的函数show()中读取变量。@drescherjm请在T age;
之后和下一个之前阅读代码示例
putvoid show(){cout Ok(){一个关键点是,在其他范围内以相同的方式命名变量,这使得变量之间没有任何联系。它们不共享值或任何东西。
#include <iostream>
using namespace std;
//Compiler version g++ 6.3.0
template<typename T>
struct Data {
T age;
};
void show();
int main()
{
Data<const int> person{
18
};
cout << person.age;
show();
}
void show(){
Data<const int> person;
cout << person.age;
}
source_file.cpp: In function ‘void show()’:
source_file.cpp:32:18: error: use of deleted function ‘Data<const int>::Data()’
Data<const int> person;
^~~~~~
source_file.cpp:10:12: note: ‘Data<const int>::Data()’ is implicitly deleted because the default definition would be ill-formed:
struct Data {
^~~~
source_file.cpp:10:12: error: uninitialized const member in ‘struct Data<const int>’
source_file.cpp:11:8: note: ‘const int Data<const int>::age’ should be initialized
T age;
^~~