为什么不能为显式模板专门化指定默认参数? [英] Why default argument cannot be specified for an explicit template specialization?

查看:149
本文介绍了为什么不能为显式模板专门化指定默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>();
}

这篇关于为什么不能为显式模板专门化指定默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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