gpt4 book ai didi

c++ - 关于 auto 作为参数类型,C++14 标准是怎么说的

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:19:19 31 4
gpt4 key购买 nike

让我们看看下面的代码:

#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 的一部分,而是 concepts-lite 的一部分。哪个may become part of C++1z根据 Herb Sutter 的上次旅行报告。

我相信 gcc 允许将此作为​​扩展,如果我们使用 -pedantic 编译您的程序,gcc 将警告:

 warning: ISO C++ forbids use of 'auto' in parameter declaration [-Wpedantic]
auto func(auto x)
^

所以从 concept-lite proposal 我们可以看出:

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();
}

因此 x 将被推断为 int。编译器会正确地给你一个错误,比如来自 gcc ( see it live ) 的错误:

error: request for member 'getx' in 'x', which is of non-class type 'int'
return x.getx();
^

提案部分 5.1.1 对此进行了介绍 [dcl.fct]:

The use of auto or a concept-name in the parameter-declaration-clause shall be interpreted as the use of a type-parameter having the same constraints and the named concept. [ Note: The exact mechanism for achieving this is unspecified. —end note ] [ Example: The generic function declared below

auto f(auto x, const Regular& y);

Is equivalent to the following declaration

template<typename T1, Regular T2>
auto f(T1 x, const T2&);

—end example ]

关于c++ - 关于 auto 作为参数类型,C++14 标准是怎么说的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33606983/

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