j4x*_*j4x 5 c++ default-value auto c++14
对于没有足够的时间进行深入调查并依赖您的帮助,我深表歉意。
\n考虑简单的代码:
\n#include <iostream>\n\nenum class PrintColour\n{\n COLOUR_1 = 0,\n COLOUR_2 = 1,\n};\n \nvoid colour( auto c = PrintColour::COLOUR_1 )\n{\n switch ( c )\n {\n case PrintColour::COLOUR_1:\n std::cout << "Colour 1" << std::endl;\n break;\n case PrintColour::COLOUR_2:\n std::cout << "Colour 2" << std::endl;\n }\n}\n\nint main( )\n{\n// colour( ); couldn\'t deduce template parameter \xe2\x80\x98auto:1\xe2\x80\x99\n colour( PrintColour::COLOUR_1 ); // Fine!\n}\nRun Code Online (Sandbox Code Playgroud)\n这段代码完全按照原样编译和运行,没有问题。但是,如果我取消注释colour( );, g++ 会引发错误:
auto_param.cpp: In function \xe2\x80\x98int main()\xe2\x80\x99:\nauto_param.cpp:27:10: error: no matching function for call to \xe2\x80\x98colour()\xe2\x80\x99\n colour( );\n ^\nauto_param.cpp:13:6: note: candidate: template<class auto:1> void colour(auto:1)\n void colour( auto c = PrintColour::COLOUR_1 )\n ^~~~~~\nauto_param.cpp:13:6: note: template argument deduction/substitution failed:\nauto_param.cpp:27:10: note: couldn\'t deduce template parameter \xe2\x80\x98auto:1\xe2\x80\x99\n colour( );\n ^\nRun Code Online (Sandbox Code Playgroud)\n有可能我只是错过了一个愚蠢的观点,或者有可能我真的很愚蠢并且误解了整件事。
\n我是否应该能够声明函数参数,同时auto仍然能够在 C++11 或 C++14 中为其指定默认值?
我认为给定的默认值足以让编译器推断出参数类型......
\n编辑1:
\n它认为我需要使我的问题更清楚,这样就不会被Is there a way to pass auto as an argument in C++? 所误解。
\n这里的重点不是传递auto给函数,而是auto与参数的默认值结合使用,这是上述问题中未考虑的事情。
编辑2:
\n正如此处注释中所澄清的,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\nauto_param.cpp:13:14: error: use of \xe2\x80\x98auto\xe2\x80\x99 in parameter declaration only available with -std=c++14 or -std=gnu++14\nRun Code Online (Sandbox Code Playgroud)\n我希望它能清楚我的问题和Is auto as a argument in a Regular function a GCC 4.9 extension?之间的区别 。如果没有请告诉我。
\n不,这是一个非推导的上下文。
非推导的上下文。
在以下情况下,用于组成 P 的类型、模板和非类型值不参与模板实参推导,而是使用在其他地方推导或显式指定的模板实参。如果模板参数仅在非推导上下文中使用并且未显式指定,则模板参数推导将失败。
<...>
4) 在函数参数的参数类型中使用的模板参数,该函数参数具有默认参数,该默认参数正在执行参数推导的调用中使用