作为模板参数传递的函数 [英] Function passed as template argument
问题描述
我正在寻找涉及传递C ++模板函数作为参数的规则。
I'm looking for the rules involving passing C++ templates functions as arguments.
这是由C ++支持的,如下所示:
This is supported by C++ as shown by an example here:
#include <iostream>
void add1(int &v)
{
v+=1;
}
void add2(int &v)
{
v+=2;
}
template <void (*T)(int &)>
void doOperation()
{
int temp=0;
T(temp);
std::cout << "Result is " << temp << std::endl;
}
int main()
{
doOperation<add1>();
doOperation<add2>();
}
但是,学习这种技术很困难。 Google搜索函数作为模板参数不会产生太多影响。而经典的 C ++模板完整指南令人惊讶地也不讨论它(至少不是从我的搜索)。
Learning about this technique is difficult, however. Googling for "function as a template argument" doesn't lead to much. And the classic C++ Templates The Complete Guide surprisingly also doesn't discuss it (at least not from my search).
我的问题是,这是否是有效的C ++(或只是一些广泛支持的扩展)。
The questions I have are whether this is valid C++ (or just some widely supported extension).
,是否有一种方法允许具有相同签名的函子在这种模板调用期间与显式函数交换使用?
Also, is there a way to allow a functor with the same signature to be used interchangeably with explicit functions during this kind of template invocation?
以下是 / strong>在上述程序中工作,至少在 Visual C ++ 中,因为语法显然是错误的。如果你想要定义一个自定义的比较操作,你可以为functor切换一个函数,反之亦然,类似于将函数指针或函子传递给std ::排序算法。 / p>
The following does not work in the above program, at least in Visual C++, because the syntax is obviously wrong. It'd be nice to be able to switch out a function for a functor and vice versa, similar to the way you can pass a function pointer or functor to the std::sort algorithm if you want to define a custom comparison operation.
struct add3 {
void operator() (int &v) {v+=3;}
};
...
doOperation<add3>();
指向一个Web链接或两个或C ++模板书中的页面的指针将不胜感激! / p>
Pointers to a web link or two, or a page in the C++ Templates book would be appreciated!
推荐答案
是的,它是有效的。
与函数一样,通常的解决方案是这样的:
As for making it work with functors as well, the usual solution is something like this instead:
template <typename F>
void doOperation(F f)
{
int temp=0;
f(temp);
std::cout << "Result is " << temp << std::endl;
}
现在可以调用:
doOperation(add2);
doOperation(add3());
这样做的问题是,如果让编译器内联调用 add2
,因为所有的编译器知道一个函数指针类型 void(*)(int&)
doOperation
。这里,编译器知道类型 add3
的一个对象,它是一个函数,被传递给函数,这意味着调用的函数是 add3 :: operator()
,而不仅仅是一些未知的函数指针。)
The problem with this is that if it makes it tricky for the compiler to inline the call to add2
, since all the compiler knows is that a function pointer type void (*)(int &)
is being passed to doOperation
. (But add3
, being a functor, can be inlined easily. Here, the compiler knows that an object of type add3
is passed to the function, which means that the function to call is add3::operator()
, and not just some unknown function pointer.)
这篇关于作为模板参数传递的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!