在C++ 17中,我们可以做类似的事情
std::pair p = {1,3}; // compiler deduces template parameters to pair<int,int>
Run Code Online (Sandbox Code Playgroud)
从cppreference的文档中我了解到以下内容不起作用:
template<class T1, class T2>
void bar(std::pair<T1,T2>)
{}
void foo()
{
bar({1,3}); // No deduction of pair template arguments
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以证实这一点,并给出一些见解,为什么这不起作用?从技术上讲这应该有效,对吧?有没有讨论过这项工作,还是有点疏忽?
Bar*_*rry 11
参考是正确的.目前采用的类模板的模板参数推导仅适用于[dcl.type.class.deduct]中的声明(和显式类型转换 - 在声明方面定义):
如果推断类类型的占位符在简单声明的decl-specifier-seq中显示为decl-specifier,则该声明的init- declarator应为
declarator-id attribute-specifier-seq opt initializer
占位符由类模板推导(13.3.1.8)的重载决策选择的函数的返回类型替换.如果init-declarator-list包含多个init-declarator,则替换占位符的类型在每次推断时应相同.[例如:
Run Code Online (Sandbox Code Playgroud)template<class T> struct container { container(T t) {} template<class Iter> container(Iter beg, Iter end); }; template<class Iter> container(Iter b, Iter e) -> container<typename std::iterator_traits<Iter>::value_type>; std::vector<double> v = { /* ... */}; container c(7); // OK, deduces int for T auto d = container(v.begin(), v.end()); // OK, deduces double for T container e{5, 6}; // error, int is not an iterator- 末端的例子]
提案或采用的措辞中没有任何关于从braced-init-list推导出类模板特化的说法.