使用统一初始化语法从函数返回元组 [英] Returning a tuple from a function using uniform initialization syntax
问题描述
以下代码使用clang(libc ++)编译,并使用gcc(libstdc ++)失败。为什么gcc(libstdc ++)抱怨初始化列表?我认为返回参数使用统一的初始化语法。
The following code compiles with clang (libc++) and fails with gcc (libstdc++). Why does gcc (libstdc++) complains about an initializer list? I thought the return argument was using uniform initialization syntax.
std::tuple<double,double> dummy() {
return {2.0, 3.0};
}
int main() {
std::tuple<double,double> a = dummy();
return 0;
}
错误:第22行:转换为'std :: tuple'from initializer \
list将使用显式构造函数'constexpr std :: tuple< _T1,_T2> :: tuple(_U1& \
& _U2&& _U1 = double; _U2 = double; = void; _T\
1 = double;注意: GCC(libstdc ++)(和clang(libc ++))accept
Error: line 22: converting to ‘std::tuple’ from initializer \ list would use explicit constructor ‘constexpr std::tuple<_T1, _T2>::tuple(_U1&\ &, _U2&&) [with _U1 = double; _U2 = double; = void; _T\ 1 = double; _T2 = double]’
/ p>
std::tuple<double,double> dummy {1.0, 2.0};
Isn't it the same case?
不一样吗?
更新::这是一个libc ++扩展,请参见 http://llvm.org/
推荐答案
不像 pair<>
,不可能遗漏构造元组
。您必须使用 make_tuple()
:
#include <tuple>
std::tuple<double,double> dummy()
{
return std::make_tuple(2.0, 3.0); // OK
}
int main()
{
std::tuple<double,double> a = dummy();
return 0;
}
std::tuple
has a variadic constructor, but it is marked as explicit
. Thus, it cannot be used in this situation, where a temporary must be implicitly constructible. Per Paragraph 20.4.2 of the C++11 Standard:
std :: tuple
有一个可变参数构造函数,但它被标记为 explicit
。因此,它不能在这种情况下使用,其中临时必须是隐式可构造的。根据C ++ 11标准的第20.4.2节:
namespace std {
template <class... Types>
class tuple {
public:
[...]
explicit tuple(const Types&...); // Marked as explicit!
template <class... UTypes>
explicit tuple(UTypes&&...); // Marked as explicit!
For the same reason it is illegal to use copy-initialization syntax for initializing tuples:
std::tuple<double, double> a = {1.0, 2.0}; // ERROR!
std::tuple<double, double> a{1.0, 2.0}; // OK
或者在将一个元组作为参数传递给函数时隐式地构造一个元组: p>
Or to construct a tuple implicitly when passing it as an argument to a function:
void f(std::tuple<double, double> t) { ... }
...
f({1.0, 2.0}); // ERROR!
f(make_tuple(1.0, 2.0)); // OK
因此,如果你构造你的 std :: tuple
显示在
dummy()
中返回时,不会发生编译错误:
Accordingly, if you construct your std::tuple
explicitly when returning it in dummy()
, no compilation error will occur:
#include <tuple>
std::tuple<double,double> dummy()
{
return std::tuple<double, double>{2.0, 3.0}; // OK
}
int main()
{
std::tuple<double,double> a = dummy();
return 0;
}
这篇关于使用统一初始化语法从函数返回元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!