C ++ 11从初始化列表到数组参数的隐式转换 [英] C++11 Implicit conversion from initialization list to array parameter
问题描述
在C ++ 11中,是否可以执行以下操作?
In C++11, is it possible to do something similar to the following?
template<typename T, size_t N>
void foo(array<T, N> src) { ... }
...
foo({1, 2, 3})
我当前正在运行GCC 4.8。
I'm currently running GCC 4.8.
推荐答案
是,我设法完成了以下工作(因为您允许类似的东西):
Yes, I managed to get the following work (since you allow something similar):
template<typename T, size_t N>
void foo(array<T, N> src) { ... }
...
foo('a', 'b');
foo(1, 2, 3);
方法如下:
#include <array>
#include <iostream>
#include <utility>
using namespace std;
template<typename T, unsigned long N>
void foo(array<T,N> src) {
for (auto e : src)
cout << e << endl;
}
template<class T, class... Tail>
auto make_array(T head, Tail... tail) -> std::array<T, 1 + sizeof...(Tail)>
{
std::array<T, 1 + sizeof...(Tail)> a = {{ head, tail ... }};
return a;
}
template<class T, class... Tail>
void foo(T&& head, Tail&&... values) {
foo(make_array(std::forward<T>(head), std::forward<Tail>(values)...));
}
int main() {
foo('a', 'b');
foo(1, 2, 3);
}
我已经用gcc 4.7.2和clang 3.4(trunk 184647)对此进行了测试),它们将按预期工作。
这是在线版本在弯曲的堆栈上。但是,此代码无法在Ideone上编译。由于无法确定在Ideone传递给编译器的选项,因此我放弃了该站点。
I have tested this with gcc 4.7.2 and with clang 3.4 (trunk 184647), they work as expected.
Here is an online version at Stacked-Crooked. However, this code fails to compile at Ideone. Since I was unable to figure out the options passed to the compiler at Ideone, I've given up on that site.
我从 @Pavel Minaev 偷了 make_array
函数>对如何使用以下方法模拟C数组初始化 int arr [] = {e1,e2,e3,…}行为的答案std :: array?问题。其他 make_array
建议导致了我无法修复的编译错误。
I have shamelessly stolen the make_array
function from @Pavel Minaev's answer to the How to emulate C array initialization "int arr[] = { e1, e2, e3, … }" behaviour with std::array? question. The other make_array
suggestions caused compile errors that I couldn't fix.
此 make_array
函数有局限性,请阅读整篇文章;特别是讨论 std :: array-如果仅知道它的大小在comp.lang.c ++。moderated上被引用。显然,要获得一个合理的 make_array
是很棘手的。 我不建议在此答案中使用思维简单的 make_array
在生产代码中使用。
This make_array
function has limitations, please read the entire post; in particular the discussion std::array - if only it knew its size on comp.lang.c++.moderated is referenced. Apparently, getting a reasonable make_array
is quite tricky. I wouldn't recommend the simple-minded make_array
in this answer to be used in production code.
如果大小是 std :: initializer_list
的模板参数,则不会有任何问题。因此,问题为什么大小不是std :: initializer_list的模板参数?
You wouldn't have any problems if the size was a template argument to std::initializer_list
. Hence the question Why is the size not a template argument of std::initializer_list?
这篇关于C ++ 11从初始化列表到数组参数的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!