[英]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. 这段代码有效( http://cpp.sh/如果你想尝试一下),但是因为我给一个函数指针作为模板参数我不需要_returnType,它就在函数签名中,问题是,没有无论我怎么努力,我都找不到摆脱这个额外模板参数的方法。
How can I make aliasGetter
take only one template parameter (a pointer to the getter to alias)? 我怎样才能使
aliasGetter
只接受一个模板参数(指向getter to alias的指针)? If that's not possible, why not? 如果那不可能,为什么不呢?
In C++17, it will become possible, thanks to template auto
: 在C ++ 17中,由于
template auto
,它将成为可能:
template <auto F> std::invoke_result_t<F> aliasGetter() { return F(); }
Before C++17, it's not possible. 在C ++ 17之前,它是不可能的。 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: C ++ 14中最短的解决方法是叹息,使用宏:
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. 它可以为您提供函数指针的类型,而无需手动输入两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.