【发布时间】:2017-09-24 09:42:00
【问题描述】:
对于没有足够的时间进行深入调查并依靠您的帮助,我深表歉意。
考虑一下简单的代码:
#include <iostream>
enum class PrintColour
{
COLOUR_1 = 0,
COLOUR_2 = 1,
};
void colour( auto c = PrintColour::COLOUR_1 )
{
switch ( c )
{
case PrintColour::COLOUR_1:
std::cout << "Colour 1" << std::endl;
break;
case PrintColour::COLOUR_2:
std::cout << "Colour 2" << std::endl;
}
}
int main( )
{
// colour( ); couldn't deduce template parameter ‘auto:1’
colour( PrintColour::COLOUR_1 ); // Fine!
}
此代码完全按原样编译和运行,没有问题。但是,如果我取消注释 colour( );,g++ 会触发错误:
auto_param.cpp: In function ‘int main()’:
auto_param.cpp:27:10: error: no matching function for call to ‘colour()’
colour( );
^
auto_param.cpp:13:6: note: candidate: template<class auto:1> void colour(auto:1)
void colour( auto c = PrintColour::COLOUR_1 )
^~~~~~
auto_param.cpp:13:6: note: template argument deduction/substitution failed:
auto_param.cpp:27:10: note: couldn't deduce template parameter ‘auto:1’
colour( );
^
可能我只是忽略了一个愚蠢的观点,或者我可能真的很愚蠢并且误解了整个事情。
我是否应该能够将函数参数声明为 auto,同时仍然能够在 C++11 或 C++14 中为其赋予默认值?
我认为给定的默认值足以让编译器推断出参数类型...
编辑 1:
它认为我需要让我的问题更清楚,以免被Is there a way to pass auto as an argument in C++?弄错
这里的重点不是将auto 传递给函数,而是将auto 与参数的默认值结合使用,上述问题中没有考虑到这一点。
编辑 2:
正如 cmets here 中所阐明的,C++11 没有将auto 作为参数传递的功能,但 C++14 及更高版本(g++ 6.3.1 默认为“gnu++14”)似乎.不过,我最初的问题与 C++11 无关,我的问题不是 C++11 是否支持 auto 参数。我依赖auto 作为参数,但忘记仔细检查它的最低标准版本。很抱歉,我现在解决了这个问题。
g++ -std=c++11 auto_param.cpp -o auto_param
auto_param.cpp:13:14: error: use of ‘auto’ in parameter declaration only available with -std=c++14 or -std=gnu++14
我希望清楚我的问题和Is auto as a parameter in a regular function a GCC 4.9 extension? 之间的区别。如果没有请告诉我。
【问题讨论】:
-
假设
auto这里只是模板参数的语法糖,你不能在没有参数的情况下调用这个函数,因为它的参数类型不能在这个上下文中推断出来。
标签: c++ c++14 default-value auto