本文介绍了initializer_list和模板类型扣除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑函数:

 模板< typename T> 
void printme(T& t){
for(auto i:t)
std :: cout<一世;
}

或任何其他函数, )启用类型。



<$>

c $ c> printme({'a','b','c'});



/ p>

  printme(std :: vector< char>({'a','b','c' 
printme(std :: string(abc));
printme(std :: array< char,3> {'a','b','c'});

我们甚至可以这样写:

  const auto il = {'a','b','c'}; 
printme(il);

  printme< std :: initializer_list< char>>({'a','b','c'}); 


解决方案

您的第一行 printme {'a','b','c'})是非法的,因为无法推断模板参数 T 。如果您明确指定模板参数,它将工作,例如。 printme< vector< char>>({'a','b','c'})或 printme< initializer_list< char> ;({'a','b','c'})。



一个定义良好的类型,所以模板参数 T 可以推导得很好。



c $ c> auto 也可以工作,因为 il 被认为是 std :: initializer_list< char> code>,因此可以推导出 printme()的模板参数。






这里唯一有趣的部分是 auto 会选择 std :: initializer_list< char> code>,但模板参数不会。这是因为C ++ 11标准的第14.8.2.5/5节明确指出这是模板参数的非推导上下文:

但是使用 auto ,§7.1.6.4/6明确支持 std :: initializer_list<>


Consider the function:

template<typename T>
void printme(T&& t) {
  for (auto i : t)
    std::cout << i;
}

or any other function that expects one parameter with a begin()/end() - enabled type.

Why is the following illegal?

printme({'a', 'b', 'c'});

When all these are legitimate:

printme(std::vector<char>({'a', 'b', 'c'}));
printme(std::string("abc"));
printme(std::array<char, 3> {'a', 'b', 'c'});

We can even write this:

const auto il = {'a', 'b', 'c'};
printme(il);

or

printme<std::initializer_list<char>>({'a', 'b', 'c'});
解决方案

Your first line printme({'a', 'b', 'c'}) is illegal because the template argument T could not be inferred. If you explicitly specify the template argument it will work, e.g. printme<vector<char>>({'a', 'b', 'c'}) or printme<initializer_list<char>>({'a', 'b', 'c'}).

The other ones you listed are legal because the argument has a well-defined type, so the template argument T can be deduced just fine.

Your snippet with auto also works because il is considered to be of type std::initializer_list<char>, and therefore the template argument to printme() can be deduced.


The only "funny" part here is that auto will pick the type std::initializer_list<char> but the template argument will not. This is because § 14.8.2.5/5 of the C++11 standard explicitly states that this is a non-deduced context for a template argument:

However with auto, § 7.1.6.4/6 has explicit support for std::initializer_list<>

这篇关于initializer_list和模板类型扣除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-06 16:40