调用参数中的类型名称T是否允许?

JeJ*_*eJo 10 c++ syntax templates language-lawyer c++11

抱歉,我无法为这个问题定一个更好的标题。

我已经为此SO帖子编写了代码;看起来像:

#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; 
}
Run Code Online (Sandbox Code Playgroud)

在那里你可以看到,我打错了(大概)

f(typename T, Ts&&... args)
//^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

但是,代码compies与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
{
^
Run Code Online (Sandbox Code Playgroud)

c

<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;
^
Run Code Online (Sandbox Code Playgroud)

真的允许这样吗?还是msvc编译器中的错误?

Dav*_*ing 5

解析器指南typename只能出现限定名称(即带有::)之前。在使用非限定名称之前,永远不需要它,因为这样的名称必须引用某些已知的声明,因此,如果确实如此,则引用类型。

GCC和Clang非常明确地表示了这一点(尽管它们在尝试从错误的解析中恢复时也会产生有用的错误)。