函数模板的默认模板参数 [英] Default template arguments for function templates

查看:111
本文介绍了函数模板的默认模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why are default template arguments only allowed on class templates? Why can't we define a default type in a member function template? For example:

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

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

Instead, C++ forces that default template arguments are only allowed on a class template.

推荐答案

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

It makes sense to give default template arguments. For example you could create a sort function:

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的此缺陷报告:功能模板的默认模板参数

C++0x introduces them to C++. See this defect report by Bjarne Stroustrup: Default Template Arguments for Function Templates and what he says


禁止功能模板的默认模板参数是一个错误遗忘的时间,其中独立函数被视为第二类

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.

限制通过不必要地使不同于成员函数的独立函数来严重地削弱编程风格,从而使得它很难编写STL样式的代码。

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

这篇关于函数模板的默认模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆