避免指定包含模板函数指针的冗余模板参数 [英] avoid specifying redundant template parameters which contain templated function pointer
问题描述
假设我们有这个代码:
template <class T, void (*u)(T&)>
void Foo()
{
// store the function u internally . . .
}
有理由做这样的事情,我不会试图去进入他们。但是,有没有办法避免在调用 Foo()
时指定 T
例如,要编译,通常需要:
There are reasons to do something like this and I won't attempt to go into them. However, is there any way to avoid having to specify type T
when calling Foo()
? For example, to compile, one normally needs:
Foo<int, MyIntFunction>();
但是如果这个 int
函数指针,这是可能的:
But if this int
can be deduced from the function pointer, is this possible:
Foo<MyIntFunction>();
EDIT 我知道解决方案传递实际的函数指针
EDIT I'm aware of the solution to pass the actual function pointer in as a function parameter, however this is not desired here as it has some perf drawbacks in intensive loop.
推荐答案
在这个例子中,这是一个函数参数,因为它在强循环中有一些缺点。 u不是函数指针,它是一个类型(函数指针的签名)。
In this example u is not a function pointer, it's a type (the signature of a function pointer). If you want to store a function pointer you need to pass it.
template<class T, class F = void(*)(T&)>
void Foo(F f)
{
// store the function pointer f here
}
这样调用:
struct SomeType {};
void bar(SomeType& x);
Foo(&bar);
这是你的意思吗?
这篇关于避免指定包含模板函数指针的冗余模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!