尝试构建任意深度树状结构的可变参数模板实例化中的无限递归

时间:2012-08-17 07:08:25

标签: c++ templates recursion c++11 variadic-templates

我正在对可变参数做一些实验,我偶然发现了一个我无法弄清楚解决方案的问题 - 基本上我正在尝试用任意数据类型的组件构建一个树 - 这里有一些代码:

template <class A, class B>
struct SeqExpression
{
    const A & first;
    const B & then;
};

template <class A, class B>
SeqExpression<A,B>
make_seq(const A & a, const B & b)
{
    return {a,b};
}

template <class A, class B, class ...T>
auto
make_seq(const A & first, const B & second, T ...rest) -> decltype(make_seq(make_seq(first,second),rest...))
{

    return make_seq(make_seq(first,second),rest...);
}

然后我尝试:

auto x = make_seq("X","Y",'z');

但GCC(4.7)告诉我:

error: template instantiation depth exceeds maximum of 900 (use -ftemplate-depth= to increase the maximum) substituting ‘template<class A, class B, class ... T> decltype (make_seq(make_seq(first, second), rest ...)) make_seq(const A&, const B&, T ...) [with A = SeqExpression<char [2], char [2]>; B = char; T = {}]’
recursively required by substitution of ‘template<class A, class B, class ... T> decltype (make_seq(make_seq(first, second), rest ...)) make_seq(const A&, const B&, T ...) [with A = SeqExpression<char [2], char [2]>; B = char; T = {}]’
required by substitution of ‘template<class A, class B, class ... T> decltype (make_seq(make_seq(first, second), rest ...)) make_seq(const A&, const B&, T ...) [with A = char [2]; B = char [2]; T = {char}]’

在我看来,它应该是可以解决的!

make_seq("X","Y")的类型为SeqExpression< char[2],char[2] > 因此make_seq(make_seq("X","Y"),'z')的类型为SeqExpression< SeqExpression< char[2],char[2] >,char >

对我来说似乎相对来说不是那么吵闹。

有什么想法吗?

0 个答案:

没有答案