how to use std::function to point to a function template

白昼怎懂夜的黑 提交于 2019-12-20 11:53:08

问题


#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;
}

回答1:


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>




回答2:


There is no such thing as a template function in C++ — what people casually mention as "template functions" are actually function templates : templates which define functions.

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.

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.




回答3:


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> ;
}



回答4:


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.



来源:https://stackoverflow.com/questions/5153148/how-to-use-stdfunction-to-point-to-a-function-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!