考虑功能:
template<typename T>
void printme(T&& t) {
for (auto i : t)
std::cout << i;
}
或任何其他需要一个参数为 begin()/end() - 启用类型的函数.
or any other function that expects one parameter with a begin()/end() - enabled type.
为什么以下内容是非法的?
printme({'a', 'b', 'c'});
当所有这些都合法时:
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
或 printme
.
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'})
.
您列出的其他参数是合法的,因为参数具有明确定义的类型,因此模板参数 T
可以很好地推导出来.
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.
带有 auto
的代码段也有效,因为 il
被认为是 std::initializer_list<char>
类型,因此模板可以推导出 printme()
的参数.
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.
唯一的搞笑"这里的部分是 auto
将选择类型 std::initializer_list
但模板参数不会.这是因为 C++11 标准的 § 14.8.2.5/5 明确指出这是模板参数的非推导上下文:
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:
一个函数参数,其关联参数是一个初始化列表 (8.5.4),但该参数没有 std::initializer_list 或对可能具有 cv 限定的 std::initializer_list 类型的引用.[示例:
A function parameter for which the associated argument is an initializer list (8.5.4) but the parameter does not have std::initializer_list or reference to possibly cv-qualified std::initializer_list type. [Example:
template<class T> void g(T);
g({1,2,3}); // error: no argument deduced for T
——结束示例 ]
但是对于 auto
,第 7.1.6.4/6 节明确支持 std::initializer_list<>
However with auto
, § 7.1.6.4/6 has explicit support for std::initializer_list<>
如果初始化器是一个 braced-init-list (8.5.4),带有 std::initializer_list
.
if the initializer is a braced-init-list (8.5.4), with
std::initializer_list<U>
.
这篇关于initializer_list 和模板类型推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!