2
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.

Waqar
  • 8,558
  • 4
  • 35
  • 43
  • The problem is not the specialization; that does have the default argument, see [here](https://godbolt.org/z/ZDyJL4). The problem is function pointers can't have default arguments, see [here](https://stackoverflow.com/questions/2225330/member-function-pointers-with-default-arguments). – cigien Jul 04 '20 at 12:53

2 Answers2

3

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);
    }
Waqar
  • 8,558
  • 4
  • 35
  • 43
1

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
}
Farhad Sarvari
  • 1,051
  • 7
  • 13
  • If you are declaring function (not defining), you can assign default values "to types", just not to come up with names of parameters for declaration, when you actually need names in definition (if I correctly understood you). – Hubert Obrzut Jul 04 '20 at 16:11