Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

templated function pointer as template parameter

I just stumbled on a small problem that bugged me while dealing with templates. Here is an example:

template<class _returnType, _returnType (*_function)()>
_returnType aliasGetter() { return _function(); }
int getCoolNumber() { return 42; }
int main()
{ 
    std::cout << aliasGetter<int, &getCoolNumber>(); //42
}

this code works (http://cpp.sh/ if you want to try it), however since I give a function pointer as template parameter I shouldn't need _returnType, it's right there in the function signature, the problem is, no matter how hard I try, I can't find a way to get rid of this additional template parameter.

How can I make aliasGetter take only one template parameter (a pointer to the getter to alias)? If that's not possible, why not?

like image 428
Nyashes Avatar asked Feb 28 '17 15:02

Nyashes


1 Answers

In C++17, it will become possible, thanks to template auto:

template <auto F> std::invoke_result_t<F> aliasGetter() { return F(); }

Before C++17, it's not possible. You need to specify the type of the non-type template parameter - there's no way around that. You can't make a factory for this either since you can't pass a function pointer through a function template and have it end up as a non-type template argument.


The shortest workaround in C++14 is to, sigh, use a macro:

template <class T, T F> std::result_of_t<T()> aliasGetter() { return F(); }
#define TEMP_ALIAS(x) decltype(x), x

std::cout << aliasGetter<TEMP_ALIAS(&getCoolNumber)>();

which gets you the type of your function pointer without you having to manually type it twice.

like image 115
Barry Avatar answered Nov 09 '22 05:11

Barry