c++ - 具有嵌套类的可变长度参数模板类

标签 c++ variadic-templates

我正在尝试编译它,但嵌套类遇到问题。

struct TKey {
    char a[2];
};

template<class TKEY, class TOBJ>
struct CHash {
    struct TNode {
        TKEY Key;
        TOBJ Obj;
    };
    int stuff;
};

template <class TKEY, class... ARGS>
class CNested : public CHash<TKEY, int> {
public:
    typedef CNested<ARGS...>            TNested;

    template<class TKEY1, class... ARGS1>
    struct TNodeType {
        typedef typename TNested::TNodeType<ARGS1...>::Type Type;
    };

    template<class TKEY>
    struct TNodeType<TKEY> {
        typedef TNode Type;
    };

    CNested() { }

};

// recursive template, tail
template <class TKEY, class TOBJ>
class CNested<TKEY, TOBJ> : public CHash<TKEY, TOBJ> {
public:
    CNested() { }
};


int main(int argc, char* argv[])
{
    // p should have type of CNested<TKey, TKey, int>::TNode*
    CNested<TKey, TKey, TKey, int>::TNodeType<TKey>* p; 
    return 0;
}

最佳答案

TNodeType 是一个依赖模板名称,因此您需要:

typedef typename TNested::template TNodeType<ARGS1...>::Type Type;
                          ^^^^^^^^

还在嵌套结构TNodeType参数TKEY中隐藏外部类CNested的参数TKEY,所以你需要更改为:

template<class TKEY1>
struct TNodeType<TKEY1> {
    typedef TNode Type;
};

关于c++ - 具有嵌套类的可变长度参数模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34007013/

相关文章:

c++ - 括号内的参数包扩展给出了奇怪的输出

c++ - 是否可以在模板类中编写一个静态可变参数模板函数,该函数可以采用 T 类型的 N 个参数?

c++ - 如何在 C++ 中为任意数量的字符串连接编写可变参数函数

php - 扩展编程技能的语言建议(针对半经验的软件开发人员)

c++ - 使用 malloc : why did it happen? 的内存分配导致堆损坏

c++ - 是否有一种干净(呃)的方式将 CRTP 与可变参数继承混合使用?

c++ - 循环可变参数模板类参数

c++ - 将可变参数函数模板参数存储到 union vector 中的最有效方法?

c++ - 为 2D vector 重载 << 和 [][]

c++ - 使用 Qt 检查字符串是否是有效的文件名