c++ - 模板特化中的默认实参参数

标签 c++ templates template-specialization default-arguments

template<typename T> void printf_t(const T&, char='\n');
template<>  void  printf_t(const  int&,     char);

void (*pi)(const int&,  char) = printf_t<int>;

int main()
{
     int a;
     scanf("%d", &a);
     pi(a);

     return 0;
}

我怎样才能让这段代码工作?我想在这个 template<int> 中有 char 参数默认值特化,但编译器表示调用函数的参数太少 pi (它期望 char )。以下代码也给出错误:

template<typename T> void printf_t(const T&, char);
template<>  void  printf_t(const  int&,     char='\n');

void (*pi)(const int&,  char) = printf_t<int>;

int main()
{
     int a;
     scanf("%d", &a);
     pi(a);

     return 0;
}

错误:

g++     template.cpp   -o template
template.cpp:55:54: error: default argument specified in explicit specialization [-fpermissive]
55 | template<>  void  printf_t(const  int&,     char='\n');
  |

当然我已经定义了printf_t<int> ,但现在它的主体已经无关紧要了。

最佳答案

How can I make this code work ?

你不能。函数指针不能采用默认参数。不过,您可以通过将调用包装到函数或 lambda 中或使用 std::bind 来解决此问题:

     auto pi = std::bind(printf_t<int>, std::placeholders::_1, '\n');
     pi(a);

使用 lambda:

     auto pi = [](const int& a) {
         printf_t<int>(a);
     };
     pi(a);

只需将其包装到函数调用中即可:

    void pi(const int& a)
    {
        printf_t<int>(a);
    }

关于c++ - 模板特化中的默认实参参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62728802/

相关文章:

c++命令行宏预处理器无法替换单词

c++ - MinGW32 链接错误 - 在一个命令中构建,但使用 Makefile 失败

c++ - 如何使此函数使用 getline 读取字符串并使其与 int 的行为相同?

C++元编程

c++ - 如何定义模板函数重载以匹配空 std::tuple<>?

c++ - 检测模板方法和自由函数的存在

c++ - 模板化类的成员函数的特化不起作用

c++ - Google Mock 和 shared_from_this 出错?

c++ - 从原始 xml 创建 xml 文件的子集,同时保持相同的结构

c++ - 多条件模板特化 C++