【发布时间】:2016-07-28 08:47:55
【问题描述】:
以下代码编译并运行:
#include <initializer_list>
#include <iostream>
#include <vector>
#include <tuple>
void ext( std::initializer_list<std::pair<double, std::vector<double> >> myList )
{
//Do something
}
///////////////////////////////////////////////////////////
int main(void) {
ext( { {1.0, {2.0, 3.0, 4.0} } } );
return 0;
}
虽然这个没有:
#include <initializer_list>
#include <iostream>
#include <vector>
#include <tuple>
void ext( std::initializer_list<std::tuple<double, std::vector<double> >> myList )
{
//Do something
}
///////////////////////////////////////////////////////////
int main(void) {
ext( { {1.0, {2.0, 3.0, 4.0} } } );
return 0;
}
唯一的区别是,在第一种情况下,ext() 函数采用 initializer_list<pair> 类型的参数(有效),而其他使用 initializer_list<tuple>(无效)。但是,cplusplus.com states that
对是元组的一种特殊情况。
那么为什么一个代码有效而另一个无效?
其他信息
clang++在第二种情况下输出的错误是:
main.cpp:33:2: error: no matching function for call to 'ext'
ext( { {1.0, {2.0, 3.0, 4.0} } } );
^~~
main.cpp:7:6: note: candidate function not viable: cannot convert initializer list argument to 'std::tuple<double,
std::vector<double, std::allocator<double> > >'
void ext( std::initializer_list<std::tuple<double, std::vector<double> >> myList )
^
1 error generated.
当 g++ 输出时:
main.cpp: In function ‘int main()’:
main.cpp:33:35: error: converting to ‘std::tuple<double, std::vector<double, std::allocator<double> > >’ from initializer list would use explicit constructor ‘constexpr std::tuple<_T1, _T2>::tuple(const _T1&, const _T2&) [with _T1 = double; _T2 = std::vector<double>]’
ext( { {1.0, {2.0, 3.0, 4.0} } } );
^
【问题讨论】:
标签: c++ tuples initializer-list std-pair