关于auto作为参数类型,C++14标准有什么规定
What does the C++14 standard say regarding auto as argument type
让我们看看下面的代码:
#include <iostream>
class Test
{
private:
int x;
public:
Test(int _x) :
x(_x)
{
std::cout << "Im being constructed" << std::endl;
}
int getx()
{
return this->x;
}
friend std::ostream& operator<<(std::ostream& os, Test& other)
{
os << other.getx();
return os;
}
};
auto func(auto x)
{
std::cout << x << std::endl;
return x.getx();
}
int main()
{
auto y = func(20);
return 0;
}
编译器如何决定(20)应该是int对象还是Test对象?Test的构造函数不是显式的,那么标准对它有什么规定呢?
因此,尽管gcc允许auto作为函数中的参数,但这不是C++14的一部分,而是概念lite的一部分。根据Herb Sutter的上一次行程报告,概念lite可能会成为C++1z的一部分。
我相信gcc允许将其作为扩展,如果我们使用-pedantic
编译您的程序,gcc将警告:
warning: ISO C++ forbids use of 'auto' in parameter declaration [-Wpedantic]
auto func(auto x)
^
因此,从概念lite提案中,我们可以看到:
auto func(auto x)
{
std::cout << x << std::endl;
return x.getx();
}
相当于:
template <typename T1>
auto func(T1 x)
{
std::cout << x << std::endl;
return x.getx();
}
因此CCD_ 2将被推导为int。编译器会正确地给你一个错误,就像下面来自gcc的错误一样(请查看实时):
error: request for member 'getx' in 'x', which is of non-class type 'int'
return x.getx();
^
提案章节5.1.1
[dcl.fct]:对此进行了说明
在参数声明子句中使用auto或概念名称应解释为使用具有相同约束和命名概念。[注:实现这一点尚未明确--尾注][示例:泛型下声明的函数
auto f(auto x, const Regular& y);
相当于以下声明
template<typename T1, Regular T2> auto f(T1 x, const T2&);
--结束示例]
auto
作为参数类型的规则与模板参数的规则相同。
auto func(auto x)
相当于template<typename T> auto func(T x)
不过,我不是引用具体规则标准的律师。
相关文章:
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- 我应该返回什么而不是标准::shared_ptr<>&?
- 如何声明一个标准::提升直方图的向量?提升直方图的类型是什么?
- 根据 c++ 标准在该宏定义中推送/弹出宏时的行为是什么
- 标准库容器最简单、性能差的哈希类是什么?
- C++ 捕获异常后进行清理的标准方法是什么?
- 读取二进制文件的惯用C++17标准方法是什么
- 在 NTL 中构造多项式的标准方法是什么?
- C++标准在[basic.scope.hiding]中"same scope"到底意味着什么?
- C++标准兼容库容器的完整接口是什么?
- 什么是正确的 macOS vscode 智能感知C++包含标准库的路径?
- 根据标准,究竟什么是"declaration of an object"
- C++标准对局部变量的存储和分配有什么保证?
- C++标准提案代码:什么是 N 和 P?
- 此代码中的数组初始化样式是什么?这是标准的吗?
- 标准库to_string(双精度)在 vs2015 中给出错误的值.有什么解决办法吗?
- Eclipse CDT 项目中的缺省C++标准是什么?
- "AfxIsValidAddress"函数的等效标准函数是什么?
- 在C++中编写符合 IEEE-754 标准的双/浮子除法的最快方法是什么?