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

后端 未结 4 986
野性不改
野性不改 2021-02-04 01:29
#include 

int func(int x, int y)
{
    return x+y;
}

int main()
{
    typedef std::function Funcp;
    Funcp funcp = func;

             


        
4条回答
  •  不知归路
    2021-02-04 01:50

    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 
    void use_function(T t) {
      typedef std::function Funcp = func;
      // 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.

提交回复
热议问题