C++ 如何使用 std::function 指向函数模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5153148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use std::function to point to a function template
提问by hidayat
#include <functional>
int func(int x, int y)
{
return x+y;
}
int main()
{
typedef std::function<int(int, int)> Funcp;
Funcp funcp = func;
return 0;
}
But is it possible to point to a template function?
但是可以指向模板函数吗?
#include <functional>
template<class T>
T func(T x, T y)
{
return x+y;
}
int main()
{
typedef std::function<?(?, ?)> Funcp;
Funcp funcp = func;
return 0;
}
回答by Victor Nicollet
There is no such thing as a template functionin C++ — what people casually mention as "template functions" are actually function templates: templates which define functions.
C++ 中没有模板函数这样的东西——人们随便提到的“模板函数”实际上是函数模板:定义函数的模板。
As such, func
in your second example above is not a function, it's a (function) template, and it cannot be used in the same way as a function can. In particular, std::function
expects to be provided with a function.
因此,func
在上面的第二个示例中,它不是函数,而是(函数)模板,并且不能像函数那样使用。特别是,std::function
期望提供一个功能。
How you can work around this depends on what you are trying to achieve. If you're trying to make the code that uses the function work with any type, you can simply place that code in a function or class template:
您如何解决此问题取决于您要实现的目标。如果您试图使使用该函数的代码适用于任何类型,您只需将该代码放在函数或类模板中:
template <typename T>
void use_function(T t) {
typedef std::function<T(T,T)> Funcp = func<T>;
// use Funcp here
}
What you will not be able to do, however, is use late binding with universal type quantifiers ("can be applied to any type"), because "can be applied to any type" is necessarily resolved at compile-time in C++. That's just how it rolls.
但是,您不能做的是使用具有通用类型量词的后期绑定(“可以应用于任何类型”),因为“可以应用于任何类型”必须在 C++ 编译时解析。它就是这样滚动的。
回答by Erik
No. A template function is exactly that, a template. It's not a real function. You can point a std::function to a specific instantiation of the template function, e.g. func<int,int>
不。模板函数就是模板。这不是一个真正的功能。您可以将 std::function 指向模板函数的特定实例,例如func<int,int>
回答by TonyK
Is this what you want?
这是你想要的吗?
#include <functional>
template<class T>
T func(T x, T y)
{
return x+y;
}
template<typename T> struct FunctionType
{
typedef std::function<T(T, T)> Type ;
} ;
int main()
{
FunctionType<int>::Type Funcp = func<int> ;
}
回答by Bj?rn Pollex
As Erik points out, this is not possible directly. To achieve the effect you probably desire, you would have to make the code that uses the pointer a template.
正如 Erik 指出的那样,这是不可能直接实现的。为了达到您可能想要的效果,您必须使使用指针的代码成为模板。