【问题标题】:Default argument parameter in template specialization [duplicate]模板特化中的默认参数参数
【发布时间】:2020-07-04 11:57:05
【问题描述】:
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&lt;int&gt; 特化中使用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&lt;int&gt;,但是它的body现在已经无关紧要了。

【问题讨论】:

  • 问题不在于专业化;确实有默认参数,请参阅here。问题是函数指针不能有默认参数,见here

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


【解决方案1】:

我怎样才能使这段代码工作?

你不能。函数指针不能采用默认参数。但是,您可以通过将调用包装到函数或 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);
    }

【讨论】:

    【解决方案2】:

    函数指针不能使用默认参数。函数的默认值也应该分配给参数,没有参数类型。

    template<int>  void  printf_t(const  int& a,     char n=  '\n')
    {
        //implementation
    }
    

    【讨论】:

    • 如果你在声明函数(不是定义),你可以将默认值“分配给类型”,只是在你真正需要在定义中的名称时(如果我正确理解你)。
    猜你喜欢
    • 2013-09-13
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多