如何根据另一个类的类型声明一个类

How to declare a class based on type of another class

本文关键字:一个 声明 类型 何根 另一个      更新时间:2023-10-16

我试图创建一个模板类的实例,基于另一个类的模板类型。但是我得到以下错误:

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

你的代码有两个问题:

  1. graph变量在分支中类型不同,声明processor时不在作用域内

  2. 访问内部类型别名的语法错误


您可以使用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)