我有两个模板类。 CCData 和 CCNode。第二个 (CCNode) 声明第一个 (CCData) 的两个实例作为其 protected 变量集的一部分。
在 cc_data.tpl.h 文件中我们有
template<class T>
class CCData
{
public:
// Constructor. Allocates memory for the values. Initialise them to
// zero
CCData(const unsigned n_values, const unsigned n_history_values=1);
.
.
.
.
};
在 cc_node.tpl.h 文件中我们有
template<class T, class DIM>
class CCNode
{
public:
// Constructor
CCNode(const unsigned n_variables, const unsigned n_history_values);
.
.
.
.
protected:
// The number of variables stored in the node
const unsigned N_variables;
// The number of history values of the variable stored in the node
const unsigned N_history_values;
// Store the spatial position of the node
CCData<double> X(DIM, N_history_values);
// Store the values of the variables stored in the node
CCData<T> U(N_variables, N_history_values);
};
cc_node.tpl.cpp 文件
template<class T, class DIM>
CCNode<T,DIM>::CCNode(const unsigned n_variables, const unsigned n_history_values)
: N_variables(n_variables), N_history_values(n_history_values)
{ }
有问题的行在 cc_node.tpl.h 文件中
// Store the spatial position of the node
CCData<double> X(DIM, N_history_values);
// Store the values of the variables stored in the node
CCData<T> U(N_variables, N_history_values);
编译器用
咆哮的地方cc_node.tpl.h:90:25: error: ‘N_history_values’ is not a type
cc_node.tpl.h:92:15: error: ‘N_variables’ is not a type
cc_node.tpl.h:92:28: error: ‘N_history_values’ is not a type
我的 gcc 版本
gcc version 5.4.0
除了
之外没有花哨的编译标志g++ -Wall -pedantic -O0 -g ...
最佳答案
您忘记的第一件事是您传递了一个类型名称 (DIM) 作为构造函数参数,但构造函数参数应该是值而不是类型名称。 另一个问题是您在 .cpp 文件中定义了模板函数(构造函数)。但是您应该在同一个头文件中定义所有模板函数以供使用。 我编辑了你的代码,它对我有用。
template<class T>
class CCData
{
public:
// Constructor. Allocates memory for the values. Initialise them to
// zero
CCData(const unsigned n_values, const unsigned n_history_values=1)
{
}
};
template<class T, class DIM>
class CCNode
{
public:
// Constructor
CCNode(const unsigned n_variables, const unsigned n_history_values):
N_variables(n_variables),
N_history_values(n_history_values),
X(n_variables,n_history_values),// pass CCData constructor arguments
U(n_variables,n_history_values)// pass CCData constructor arguments
{}
protected:
// The number of variables stored in the node
const unsigned N_variables;
// The number of history values of the variable stored in the node
const unsigned N_history_values;
// Store the spatial position of the node
CCData<double> X;//(DIM, N_history_values); -> DIM is a type name not a value
// Store the values of the variables stored in the node
CCData<T> U;//(N_variables, N_history_values);
};
您必须将构造函数定义放在同一个头文件中。因为编译器在编译时需要模板函数定义。
关于C++ 模板 "is not a type"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42847091/