如何声明自引用模板typedef

时间:2015-08-13 18:38:18

标签: c++ templates c++11

这是一个小例子,它与我正在尝试的内容大致相似:

#include <boost/variant/variant.hpp>
#include <boost/variant/recursive_wrapper.hpp>
#include <utility>
#include <vector>

struct foo {
    const char * str;
};

typedef std::pair<float, float> fpair;

//typedef std::vector<boost::variant<int, fpair, foo, vlist>> vlist;
// ^ No...

//typedef std::vector<boost::variant<int, fpair, foo, boost::recursive_wrapper<vlist>>> vlist;
// ^ No...

//template <typename T = vlist<T> >
//using vlist = std::vector<boost::variant<int, fpair, foo, boost::recursive_wrapper<vlist>>>;
// ^ No...

template <typename T = vlist<T> >
using vlist = std::vector<boost::variant<int, fpair, foo, boost::recursive_wrapper<T>>>;
// Still no?

int main () {
    std::cout << "Hello world\n";
}

我用gcc 4.8得到的错误是:

test.cpp:12:33: error: expected nested-name-specifier before ‘vlist’
template <typename T = typename vlist<T>>
                                ^
test.cpp:12:33: error: expected ‘>’ before ‘vlist’

clang 3.6的错误是:

test.cpp:12:24: error: unknown type name 'vlist'
template <typename T = vlist<T>>
                       ^
test.cpp:12:29: error: expected ',' or '>' in template-parameter-list
template <typename T = vlist<T>>
                            ^
test.cpp:12:32: error: expected unqualified-id
template <typename T = vlist<T>>
                               ^
3 errors generated.

(编辑:实际上这些错误来自上述代码的略有不同的版本,但它们都提供了非常相似的消息)

我看了这些早先略有不同的问题,我仍然难过:

How to declare a self referencing template type

How to properly declare a self-referencing template type?

Boost Fusion adapt declaration for a templated self referential structure

有没有人知道这个技巧,或者是否有某些原因我不知道编译器固有地无法做到这一点?

1 个答案:

答案 0 :(得分:2)

我相信你只想要boost::make_recursive_variant

#include <boost/variant/variant.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <utility>
#include <vector>

struct foo {
    const char* str;
};

typedef std::pair<float, float> fpair;

typedef boost::make_recursive_variant<
    int,
    fpair,
    foo,
    std::vector<boost::recursive_variant_>
>::type vlist;

int main() {
    std::vector<vlist> vec;
    vec.push_back(4);
    vec.push_back(fpair{1.0f, 2.0f});

    vlist v2(vec);
}