如何根据另一个类的类型声明一个类
How to declare a class based on type of another class
我试图创建一个模板类的实例,基于另一个类的模板类型。但是我得到以下错误:
error: template argument 1 is invalid
template <typename IdType>
class GraphNode
{
IdType id;
};
template <typename IdType>
class Graph
{
public:
using NodeType = IdType;
GraphNode<IdType> nodes[100];
};
template <typename IdType>
class ProcessGraph
{
//some functions
};
template <typename IdType>
auto create_graph()
{
Graph<IdType> graph;
// populate graph here
return graph;
}
int main(int argc, char *argv[])
{
if(atoi(argv[1]))
const auto &graph = create_graph<int>();
else
const auto &graph = create_graph<unsigned long>();
auto processor = ProcessGraph<typename graph.NodeType>(); // The error occurs here
return 0;
}
Thanks for help
你的代码有两个问题:
-
graph
变量在分支中类型不同,声明processor
时不在作用域内 -
访问内部类型别名的语法错误
您可以使用decltype(x)
检索变量x
的类型。由于graph
是一个引用,您需要使用std::remove_reference_t
删除引用。然后,您可以使用::NodeType
来检索内部类型别名。
if(atoi(argv[1]))
{
const auto &graph = create_graph<int>();
auto processor = ProcessGraph<
std::remove_reference_t<decltype(graph)>::NodeType>();
}
else
{
const auto &graph = create_graph<unsigned long>();
auto processor = ProcessGraph<
std::remove_reference_t<decltype(graph)>::NodeType>();
}
如果您想重构代码以避免重复,请将初始化processor
变量的代码放在template
函数中,该函数将graph
作为参数(或者在其主体中使用用户定义类型创建graph
)。
相关文章:
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 在C++中声明一个函数时,它需要有函数本身的参数吗
- C++ 警告:在一个声明中将截断从双精度初始化为浮点数,但在另一个声明中则不初始化
- 在c++中的复制构造函数/一个声明语句中的初始化的延续中使用chain方法
- 错误:"int pow(double,int)"与上一个声明int pov(double a,int
- 为什么一个接一个声明的两个变量在内存中不相邻?
- 如何创建一个声明来自另一个类的变量的类
- 如何在c 中留下一个声明的函数,例如haskell中的``undefined''
- 来自上一个声明的 G++ 错误,由于包含中的函数名称重复而导致的错误
- 将内部类名声明为另一个声明的一部分
- 添加两个整数,但一个声明为"int",另一个声明为"auto"?
- 一个声明中多个函数的原型
- 强制构造像“Foo(12,3);”这样的未命名变量仍然是一个声明符
- 错误:一个声明中有多个类型
- 在一个声明中出现多个类型的问题
- 变量的地址是不是一个接一个声明,一个接一个
- c++错误:在一个声明中包含多个类型
- if语句的分支不能仅仅是一个声明
- visual studio 2010 -智能感知:期望在c++中有一个声明