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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.