功能模板专业化的别名 [英] Alias to a function template specialization
问题描述
int f1(int a, int b) { return a+b; }
int f2(int a, int b) { return a*b; }
template <typename F> void foo(int i, int j)
{
// do some processing before
F(i,j);
// do some processing after
}
我想做个别名
constexpr auto foo1 = &foo<f1>;
constexpr auto foo2 = &foo<f2>;
并调用如下函数: foo1(1,2); foo2 (1,2);
用C ++可以做到这一点吗?谢谢!
and call the function like this: foo1(1,2);foo2(1,2);
Any way to achieve this in C++? Thanks!
编辑:
foo()不是f1的包装,它是调用f1或f2的函数。在通话之前和之后,我需要做一些额外的事情。 F是个函子,我想对foo的专业化做一个捷径。 上面的代码是伪代码。
推荐答案
注释中有一些好的方法: std :: bind,使用lambda,将 F
的实例传递到函数中,因此我将提供替代方法。
There are some good approaches in the comments: std::bind, using a lambda, passing an instance of F
into the function, so I'll provide an alternative.
如果要传递给 foo
的函数类型始终为 int(int,int)
,然后将template参数设为非类型模板参数,然后使用您的函数之一实例化它:
If the function type that you will pass into foo
will always be int(int, int)
, then you make the template parameter be a non-type template parameter, and then instantiate it with one of your functions:
int f1(int a, int b) { std::cout<<"f1\n"; return a+b; }
int f2(int a, int b) { std::cout<<"f2\n"; return a*b; }
template <int(*F)(int, int)>
void foo(int i, int j)
{
F(i,j);
}
然后这样称呼它:
int main()
{
constexpr auto foo1 = foo<f1>;
constexpr auto foo2 = foo<f2>;
foo1(1,2);
foo2(1,2);
}
输出:
f1
f2
f1
f2
我们在这里做的技巧是我们正在将template参数作为对函数的引用,该函数是hacky但合法的AFAIK。
The trick we're doing here is that we're making the template parameter be a reference to a function, which is hacky but legal AFAIK.
这篇关于功能模板专业化的别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!