gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:09:23 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com