Bubaya
Bubaya

Reputation: 823

Automatic template deduction for function pointers

In the following code

template<class T> void f(T);
int main(){
    f(3);
    return 0;
}

the template argument int for deduces automatically, as usual.

But in

template<class T> void f(T);
template<class T> void (*p)(T) = f<T>;

int main(){
    p(3);
    return 0;
}

the compiler (clang++) insists that p(3) needs a template parameter. Why?

Besides, if I put the line template<class T> void (*p)(T) = f<T>; in a header to be included by several files, will that cause problems?

Upvotes: 0

Views: 195

Answers (1)

user19946454
user19946454

Reputation:

Template argument deduction works with function templates and and with CTAD from C++17. Writing a wrapper is trivial for your example.

template<class T> void f(T);
template<class T> void (*p)(T) = f<T>;


template<typename T> void Wrapper(T&& t)
{
    p<T>(std::forward<T>(t));
}

int main(){
    Wrapper(3);
}

Upvotes: 5

Related Questions