c++ - 为什么不能为显式模板特化指定默认参数?

标签 c++ templates

下面的代码无法通过编译,这个编译错误是什么考虑?

template<class T> void f(T t) {};

template<> void f<char>(char c = 'a') {}

错误消息:函数模板的显式特化不允许使用默认参数

最佳答案

我认为这个错误背后的原因是函数模板中的默认参数也适用于它的特化,并且你不能在 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 表示使用主模板中定义的默认参数调用特化。

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

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

关于c++ - 为什么不能为显式模板特化指定默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4050202/

相关文章:

c++ - 创建指向 "this"对象的指针

c++ - Qt 用例将相同信号发送到同一对象上的 2 个插槽?

json - Azure APIM-无法访问液体模板中的 json 正文值

c++ - 为什么显式给出的模板参数不能为 “deduced”

c++ - 类模板特化,C++,模板参数列表中的参数 2 不匹配

c++ - 1.#QNAN错误C++

c++ - SetThreadContext x64 volatile 寄存器

c++ - 如何将 UUID 转换为大端?

c++ - 无法推断 'T' 的模板参数

c++ - 组合或替换多个相似的重载