C++ 变量类型条件

标签 c++ c++11 types

我有两个类 TreeNodeRange(Tree & t)VertexNodeRange(Vertex & v)。遍历第一个等于遍历树中的所有节点,而遍历第二个等于遍历给定顶点 v 的子节点的所有节点。

现在根据用户输入,我想遍历整棵树或只遍历从 v 开始的子树。

我试过这样的:

const bool only_subtree = to_bool(argv[1]);
typedef std::conditional<only_subtree, VertexNodeRange,TreeNodeRange>::type NodeRange; 

现在的问题是我不知道如何定义 NodeRange 类型的对象。我试过:

Vertex v = tree.get_vertex_by_id(17);
NodeRange get_range = [&](const bool only_subtree, Vertex & v)
    {
        if(only_subtree) return NodeRange(v);
        return NodeRange(tree);
    };
for(auto node : get_range(only_subtree, v)){
    ...
}

编译器似乎不喜欢这样,因为构造函数 NodeRange 必须可以用 Vertex 或 Tree 调用,当然它不能。

有没有办法在 C++ 中做到这一点?

干杯

最佳答案

你可以做一个模板函数:

template<typename AnyNodeRange>
void processChildNodes(AnyNodeRange& anyNodeRange)
{
    for(auto node : anyNodeRange){
    ...
    }
}

并像这样使用它:

Vertex v = tree.get_vertex_by_id(17);
if (only_subtree) {
    VertexNodeRange vertexNodeRange(v);
    processChildNodes(vertexNodeRange);
}
else 
{
    TreeNodeRange treeNodeRange(tree);
    processChildNodes(treeNodeRange);
}

您不能使用 only_subtree 创建 typedef,因为它是用户输入,仅在运行时才知道,而类型仅在编译时定义。

关于C++ 变量类型条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45420532/

相关文章:

c++ - 在编译时获取静态 constexpr 数组的最小值/最大值

c++ - 常量数组的自动引用

C 中类型之间的转换

database - DBI:如何为未知数据找到正确的数据类型?

c++ - 获取给定对象的类型说明符

c++ - 在 C++ 中有一个包含不同类型键的映射

c++ - C/C++ 声音操作系统 API

C++11 观察者模式(信号、槽、事件、改变广播器/监听器,或任何你想调用它的东西)

c++ - 为随机生成的字符串 C/C++ 打印字符,不在随机列表中的字符也被打印

c++ - 在其自身的默认值中使用参数名称 - 合法吗?