使用中的模板参数包

时间:2019-08-19 17:21:24

标签: c++ visual-c++ variadic-templates using

当参数包是基类的模板参数时,如何在多重继承中使用“使用”关键字?

下面的代码可以正常编译

struct A
{
    void foo(int) {}
};

struct B
{
    void foo(int) {}
};

template<typename ...Types>
struct C : public Types...
{
   using Types::foo...;
};

int main()
{
    C<A,B> c;
}

但是如果我使用模板而不是AB-我会遇到编译错误

template<typename T> 
struct TA {};

template<>
struct TA<int>
{ 
    void foo(int) {} 
};

template<>
struct TA<double>
{
    void foo(int) {}
};

template<typename ...Types>
struct TC : public TA<Types>...
{
    using TA<Types>::foo...; // ERROR C3520
};

错误:

error C3520: 'Types': parameter pack must be expanded in this context

如何重写第二段代码以使其正常工作?

PS 我用gcc尝试了这段代码,并且编译时没有错误。但是现在我正在使用msvc ...

1 个答案:

答案 0 :(得分:1)

由于它是known MSVC bug,因此,如果您仍然想使用MSVC进行此操作,则必须以(不是很困难的)方式来做到这一点:

template <typename ...Types>
struct TC;

template <typename T>
struct TC<T> : TA<T>
{
    using TA<T>::foo;
};

template <typename T, typename ...Types>
struct TC<T, Types...> : public TC<T>, public TC<Types...>
{
    using TC<T>::foo;
    using TC<Types...>::foo;
};