对不起,我无法为这个问题找到更好的标题。
我为this SO post写了一个代码;看起来像:
#include <iostream>
#include <string>
#include <type_traits>
template < typename T, typename ...Ts> T f(const T &a, Ts&&... args)
{
return a;
}
template < typename R, typename T, typename... Ts>
typename std::enable_if<!std::is_same<R, T>::value, R>::type
f(typename T, Ts&&... args)
//^^^^^^^^^^ --->HERE
{
return f<R>(std::forward<Ts>(args)...);
}
int main() {
std::cout << f<int>('a', std::string{ "string" }, 12);
return 0;
}
在那里你可以看到,我做了一个错字(大概)
f(typename T, Ts&&... args)
//^^^^^^^^^^
但是,当msvc v19.14时,代码与-O3 -std=c++11
匹配。
另一方面,GCC和clang提供编译器错误:https://godbolt.org/z/HugROb
来自GCC:
error : 'template<class R, class T, class ... Ts> typename std::enable_if<(! std::is_same< <template-parameter-1-1>, <template-parameter-1-2> >::value), R>::type f' conflicts with a previous declaration
typename std::enable_if<!std::is_same<R, T>::value, R>::type f(typename T, Ts&&... args)
^ ~~~~~~~
note : previous declaration 'T f(T, Ts&& ...)'
template < typename T, typename ...Ts> T f(T a, Ts&&... args)
^
error : expected nested - name - specifier before 'T'
typename std::enable_if<!std::is_same<R, T>::value, R>::type f(typename T, Ts&&... args)
^
error : expected '(' before 'T'
error : expected primary - expression before '&&' token
typename std::enable_if<!std::is_same<R, T>::value, R>::type f(typename T, Ts&&... args)
^ ~
warning : variable templates only available with - std = c++14 or -std = gnu++14
typename std::enable_if<!std::is_same<R, T>::value, R>::type f(typename T, Ts&&... args)
^
error : expected ';' before '{' token
{
^
来自clang:
<source>:13 : 74 : error : expected a qualified name after 'typename'
typename std::enable_if<!std::is_same<R, T>::value, R>::type f(typename T, Ts&&... args)
^
<source> : 13 : 74 : error : expected a qualified name after 'typename'
<source> : 13 : 74 : error : expected ')'
<source> : 13 : 64 : note : to match this '('
typename std::enable_if<!std::is_same<R, T>::value, R>::type f(typename T, Ts&&... args)
^
<source> : 15 : 34 : error : use of undeclared identifier 'args'; did you mean 'abs' ?
return f<R>(std::forward<Ts>(args)...);
^~~~
abs
/ usr / include / stdlib.h:837 : 12 : note : 'abs' declared here
extern int abs(int __x) __THROW __attribute__((__const__)) __wur;
^
是真的允许这样吗?或者它是msvc编译器中的错误?
解析器指南typename
可以出现only before一个合格的名称(即,使用::
)。在非限定名称之前永远不需要它,因为这些名称必须引用某些已知的声明,因此如果它们存在,则称为类型。
GCC和Clang非常明确地说明了这一点(尽管每次尝试从错误的解析中恢复时都会产生较少的错误)。