函数参数的C++类模板推导(P0091R0)

Flo*_*mid 15 c++ c++17

在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,则替换占位符的类型在每次推断时应相同.[例如:

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
Run Code Online (Sandbox Code Playgroud)

- 末端的例子]

提案或采用的措辞中没有任何关于从braced-init-list推导出类模板特化的说法.