c++ - 函数模板的默认模板参数

标签 c++ templates

为什么默认模板参数只允许在类模板上使用?为什么我们不能在成员函数模板中定义默认类型?例如:

struct mycclass {
  template<class T=int>
  void mymember(T* vec) {
    // ...
  }
};

相反,C++ 强制默认模板参数只允许在类模板上使用。

最佳答案

提供默认模板参数是有意义的。例如,您可以创建一个排序函数:

template<typename Iterator, 
         typename Comp = std::less<
            typename std::iterator_traits<Iterator>::value_type> >
void sort(Iterator beg, Iterator end, Comp c = Comp()) {
  ...
}

C++0x 将它们引入 C++。请参阅 Bjarne Stroustrup 的缺陷报告:Default Template Arguments for Function Templates以及他说的话

The prohibition of default template arguments for function templates is a misbegotten remnant of the time where freestanding functions were treated as second class citizens and required all template arguments to be deduced from the function arguments rather than specified.

The restriction seriously cramps programming style by unnecessarily making freestanding functions different from member functions, thus making it harder to write STL-style code.

关于c++ - 函数模板的默认模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15447611/

相关文章:

c++ - std::make_unsigned 没有给出预期的结果

c++ - 模板模板参数和 clang

c++ - 裁剪函数 BitBlt(...)

c++ - 将别名模板传递给它所依赖的模板的基类

c++ - 是否允许在同一个 Sqlite 数据库连接中启动多个事务?

C++ 使用可变参数模板绑定(bind)成员函数

c++ - 将 void* 转换为具有多重继承的类

c++ - 奇怪的模板构造函数语法

c++ - 如何正确地使模拟方法调用原始虚方法

c++ - 如何找到计算机的 IP 地址?