gpt4 book ai didi

c++ - 具有默认值的参数的自动类型推导

转载 作者:搜寻专家 更新时间:2023-10-31 00:54:57 26 4
gpt4 key购买 nike

对于没有足够的时间进行深入调查并依赖您的帮助,我深表歉意。

考虑简单的代码:

#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:

正如此处评论中所阐明的,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? 之间的区别.如果没有请告诉我。

最佳答案

不,it is a non-deduced context .

Non-deduced contexts.

In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.

<...>

4) A template parameter used in the parameter type of a function parameter that has a default argument that is being used in the call for which argument deduction is being done

关于c++ - 具有默认值的参数的自动类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43643473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com