将函数参数类型声明为 auto
Declaring function parameter type as auto
我正在使用 GCC 6.3,令我惊讶的是,以下代码片段确实可以编译。
auto foo(auto x)
{
return 2.0*x;
}
....
foo(5);
据我所知,它是 GCC 扩展。与以下比较:
template <typename T, typename R>
R foo(T x)
{
return 2.0*x;
}
除了return类型推导,上面的声明是否等价?
Using the same GCC (6.3) with the -Wpedantic
flag 将生成以下警告:
warning: ISO C++ forbids use of 'auto' in parameter declaration [-Wpedantic]
auto foo(auto x)
^~~~
While compiling this in newer versions of GCC,即使没有 -Wpedantic
,也会生成此警告,提醒您关于 -fconcepts
标志:
warning: use of 'auto' in parameter declaration only available with -fconcepts
auto foo(auto x)
^~~~
Compiler returned: 0
确实,concepts 做到了:
void foo(auto x)
{
auto y = 2.0*x;
}
相当于:
template<class T>
void foo(T x)
{
auto y = 2.0*x;
}
See here: "If any of the function parameters uses a placeholder (either auto
or a constrained type), the function declaration is instead an abbreviated function template declaration: [...] (concepts TS)" -- 强调我的。
我正在使用 GCC 6.3,令我惊讶的是,以下代码片段确实可以编译。
auto foo(auto x)
{
return 2.0*x;
}
....
foo(5);
据我所知,它是 GCC 扩展。与以下比较:
template <typename T, typename R>
R foo(T x)
{
return 2.0*x;
}
除了return类型推导,上面的声明是否等价?
Using the same GCC (6.3) with the -Wpedantic
flag 将生成以下警告:
warning: ISO C++ forbids use of 'auto' in parameter declaration [-Wpedantic]
auto foo(auto x)
^~~~
While compiling this in newer versions of GCC,即使没有 -Wpedantic
,也会生成此警告,提醒您关于 -fconcepts
标志:
warning: use of 'auto' in parameter declaration only available with -fconcepts
auto foo(auto x)
^~~~
Compiler returned: 0
确实,concepts 做到了:
void foo(auto x)
{
auto y = 2.0*x;
}
相当于:
template<class T>
void foo(T x)
{
auto y = 2.0*x;
}
See here: "If any of the function parameters uses a placeholder (either auto
or a constrained type), the function declaration is instead an abbreviated function template declaration: [...] (concepts TS)" -- 强调我的。