Variadic模板表现得很奇怪

时间:2011-10-23 21:51:41

标签: c++ compiler-errors c++11 intel variadic-templates

我想知道我做错了什么或者这是否是编译错误。我正在使用英特尔C ++ Composer XE 2011 for Windows SP1(或更新6,这是目前最新的)。请参阅代码中的注释行。

#include <tchar.h>
#include <iostream>
#include <conio.h>

template <typename ...T>
struct first_va_arg {};

template <typename T0, typename ...T_>
struct first_va_arg<T0, T_...> {
    typedef T0    type;
};

template <typename ...T>
inline first_va_arg<T...>::type getFirstArgTypeDefaultValue( const T& ...values )
{
//Next line causes error: nontype "first_va_arg<T...>::type [with T=<T...>]" is not a type name
    typedef first_va_arg<T...>::type    FirstArgT;
    return FirstArgT();
//It works correctly if you comment out the above two lines and uncomment the single line below
    //return first_va_arg<T...>::type();
}


int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << getFirstArgTypeDefaultValue(5.67, 32) << std::endl;
    _getch();
    return 0;
}  

1 个答案:

答案 0 :(得分:3)

由于你有依赖名称,你需要说typename

template <typename ...T> inline typename first_va_arg<T...>::type getFirstArgTypeDefaultValue( const T& ...values )
//                              ^^^^^^^^
{
  typedef typename first_va_arg<T...>::type FirstArgT;
  //..
}

请注意,您缺少 no 参数的基本情况。我可能会取消部分特化,只需将主模板声明为:

template <typename T, typename...> struct first_va_arg  { typedef T type; };

然后,当您说first_va_arg<>::type时,您没有收到“不存在的名称”错误,但可能更有意义的“模板参数不匹配”。由你决定。或者,您只能声明主模板,但保留未定义。