Default argument parameter in template specialization

Viewed 191
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;
}

How can I make this code work ? I want to have char argument default value in this template<int> specialization, but compiler says there is too few arguments to call function pi (it expects char). Also following code gives error:

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

Error:

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');
  |

Of course I have defined printf_t<int>, but it's body is irrelevant now.

2 Answers

How can I make this code work ?

You can't. Function pointers can't take default arguments. You can, however, workaround it by either wrapping the call into a function or lambda or using std::bind:

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

Using a lambda:

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

Just wrapping it into a function call:

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

You can not use default parameter for function pointer. Also default value for function should be assigned to parameter no type of the parameters.

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