简体   繁体   English

C++11中auto关键字的编译错误

[英]Compilation error in auto keyword in C++11

I know that the use of auto keyword can automatically deduce the type of the variable from the Rvalue.我知道使用auto关键字可以自动从 Rvalue 推断变量的类型。 Then why does the following function snippet in my code have a compilation error?那为什么我的代码中下面的函数片段会出现编译错误呢?

auto getName(auto str = "John Doe") {
    return str;
}

The compilation error is 'auto' not allowed in function prototype.编译错误是函数原型中不允许的“自动”。 I googled a bit and I think auto can not be used in the function prototypes.我用谷歌搜索了一下,我认为auto不能在函数原型中使用。 Why So?为什么这样?

You can use auto in a lambda expression, but not a normal function.您可以在 lambda 表达式中使用auto ,但不能在普通函数中使用。

To get the same effect, you can define a function template instead:为了获得相同的效果,您可以定义一个函数模板:

template <class T>
T getname(T input = "John Doe") {
    return input;
}

But be aware that this default value for the argument will only work for types that can actually be initialized from a string literal.但请注意,该参数的默认值仅适用于实际上可以从字符串文字初始化的类型。

Oh, and as an aside, names starting with str are reserved, so it would be better to use a different name.哦, str一句,以str开头的名称是保留的,因此最好使用不同的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM