initializer_list< T>无法转换为initializer_list< U> ;,但T可转换为U [英] initializer_list<T> can't convert to initializer_list<U>, but T convertable to U
问题描述
考虑以下代码段...
Considering the following code snippet...
void boo(std::initializer_list<unsigned> l)
{
}
template <class T>
void foo(std::initializer_list<T> l)
{
//Even though T is convertable, initializer list is not...:-(
boo(move(l));
}
int main()
{
foo({1u,2u,3u}); //Compiles fine as expected
foo({1,2,3}); //Fails to compile at line 9... - could not convert...
return 0;
}
...我很惊讶 initializer_list< int>
不能转换为 initializer_list< unsigned>
,尽管int会转换为unsigned.
... I'm surprised that initializer_list<int>
is not convertible to initializer_list<unsigned>
, event though int converts to unsigned.
我一直想知道可以通过哪种方式编写foo来允许转换.可以以某种方式解开类型错误的列表并重新创建具有正确类型的新列表吗?
I've been wondering in what way one can write foo to allow the conversion. Can one somehow unwrap the list having the wrong type and recreate a new list with the right type?
推荐答案
尽管在编译期间无法解包初始值设定项列表(以执行必要的转换),但是可以按照自己的方式创建它.考虑以下代码:
While you can't unpack initializer list during compile time (to perform neccessary conversion), you can create it the way you want it to be. Consider following code:
#include <initializer_list>
void boo(std::initializer_list<unsigned> l);
template <class... T>
void foo(T... l)
{
boo({static_cast<unsigned int>(l)...});
}
int main()
{
foo(1,2,3);
return 0;
}
这篇关于initializer_list< T>无法转换为initializer_list< U> ;,但T可转换为U的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!