Why does this variadic template specialization definition not compile?

亡梦爱人 提交于 2019-12-07 20:04:52

问题


Using gcc 4.7.3, I get the following error

prog.cpp: In function ‘int main()’: prog.cpp:27:63: error: ‘Erase >::Result’ has not been declared

with this code:

template <typename... List>
struct TypeList
{
    enum
    {
        Length = sizeof...(List)
    };
};

template <typename ToErase, typename... List>
struct Erase;

template <typename ToErase>
struct Erase<ToErase, TypeList<>>
{
    typedef TypeList<> Result;
};

template <typename ToErase, typename... Head, typename... Tail>
struct Erase<ToErase, TypeList<Head..., ToErase, Tail...>>
{
    typedef TypeList<Head..., Tail...> Result;
};

int main()
{
    static_assert(Erase<double, TypeList<int, double, char>>::Result::Length == 2, 
    "Did not erase double from TypeList<int, double, char>");

    return 0;
}

I don't understand why the code doesn't compile given the error message I've received, given that a similar case does compile cleanly:

template <typename ToAppend, typename... List>
struct Append;

template <typename ToAppend, typename... List>
struct Append<ToAppend, TypeList<List...>>
{
    typedef TypeList<List..., ToAppend> Result;
}

template <typename... ToAppend, typename... List>
struct Append<TypeList<ToAppend...>, TypeList<List...>>
{
    typedef TypeList<List..., ToAppend...> Result;
}

Is there a quote from the standard about not being able to deduce elements in the middle of two parameter packs like I'm trying to do with the first block of code?


回答1:


§ 14.8.2.5 (Deducing template arguments from a type) paragraph 5 lists the contexts in which template arguments cannot be deduced. The relevant one is the last one in the list:

— A function parameter pack that does not occur at the end of the parameter-declaration-clause.

So in:

struct Erase<ToErase, TypeList<Head..., ToErase, Tail...>>

Head cannot be deduced; it does not occur at the end of a parameter list.

By contrast, in:

struct Append<TypeList<ToAppend...>, TypeList<List...>>

Both ToAppend and List appear at the end of their respective parameter lists, and hence they can be deduced.



来源:https://stackoverflow.com/questions/17332286/why-does-this-variadic-template-specialization-definition-not-compile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!