以下代码编译并运行:
#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说明:
pair是tuple的一种特殊情况。
那么为什么一段代码可用而另一段不行呢?
额外信息
第二种情况下,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} } } );
^