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

时间:2015-11-30 20:06:16

标签: 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;
}

1 个答案:

答案 0 :(得分:3)

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

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

同样在嵌套的struct TNodeType参数TKEY中,外部TKEY的参数class CNested也会出现影响,因此您需要更改为:

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