为什么不能为显式模板专门化指定默认参数?

编程入门 行业动态 更新时间:2024-10-09 07:25:37
本文介绍了为什么不能为显式模板专门化指定默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下代码无法通过编译,这个编译器错误的注意事项是什么?

The below code couldn't pass the compilation, what's the consideration for this compiler error?

template<class T> void f(T t) {}; template<> void f<char>(char c = 'a') {}

错误消息:不允许对函数模板的显式专门化

Error message: Default arguments are not allowed on an explicit specialization of a function template

推荐答案

我认为这个错误背后的理由是由于函数模板中的默认参数也适用于其专业化,并且不允许在C ++中多次定义默认参数。

I think that the rationale behind this error is due to the fact that the default arguments in the function template apply to its specialization as well and you are not allowed to define the default argument more than once in C++.

请考虑以下内容:

#include <iostream> template<class T> void f(T t = 'a') {} template<> void f<char>(char c) { std::cout << c << std::endl; } int main(int argc, char **argv) { f<char>(); }

这将打印 a

如果您需要为每个专业化使用不同的默认参数,您可以使用如下所示的方法:

If you need a different default argument for each specialization you can use the approach illustrated below:

#include <iostream> template<class T> struct default_arg { static T get() { return T(); } }; template<class T> void f(T t = default_arg<T>::get()) {} template<> struct default_arg<char> { static char get() { return 'a'; } }; template<> void f<char>(char c) { std::cout << c << std::endl; } int main(int argc, char **argv) { f<char>(); }

更多推荐

为什么不能为显式模板专门化指定默认参数?

本文发布于:2023-11-23 13:18:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621580.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能为   模板   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!