c++ 我们可以像定制类中的std::函数那样使用模板类型吗

kxe2p93d  于 2023-03-14  发布在  其他
关注(0)|答案(2)|浏览(134)

我正在学习一些基本的cpp,我发现我们可以将lambda函数传递给一个接受std::函数的函数,如下所示:

int someFunction(std::function<int(int, int)> sum) {
  return sum(1,3);
}

我很困惑std::函数是如何将模板类型作为“int(int,int)”的,通常我只看到类接受像someClass〈int,int〉这样的类型。
我们如何定义采用“int(int,int)"这样的模板类型的类?
我试着声明类

template<typename A(typename B)> // --> this just gives an syntax error.
class SomeClass {};
eoigrqb6

eoigrqb61#

首先,您的示例不应编译。

int someFunction(std::function<int(int)> sum) {
  return sum(1,3);
}

/*
std::function<int(int)>
              ^    ^
              |    |
           return  parameter
            type  

So, calling sum(1,3) would require function<int(int, int) as you are passing two parameters and returning a value.
*/

更多示例

/*
The structure is "return_type(param1, param2, ..)" for the function and the following 
`[]` is used for variable capture (by value [x] or by reference [&x]) that resides out the function.
*/

// takes one param and returns nothing
function<void(int)> print = [](auto i) {
   court<<i<<endl;
}

// takes two params and returns the sum
function<int(int, int)> sum = [](auto i, auto j) {
   return i + j;
}

// takes one param and returns with added 2
function<int(int)> sum = [](auto i) {
   return i + 2;
}

我们如何定义采用“int(int,int)"这样的模板类型的类?

template<typename T>
class Class {
  public:
    void call(T sum) {
      cout << sum(1, 3) << endl;
    } 
};

// usage
auto sum = [](auto a, auto b) { return a + b; };
auto instance = new Class<decltype(sum)>();
instance->call(sum);
ttcibm8c

ttcibm8c2#

感谢@Raildex的评论,我回答了我自己的问题。基本上,问题中的int(int,int)类型将引用一个函数指针,该指针接受2个int并返回一个int。
因此,示例类可以是:

template<typename T>
class SomeClass {
  public:
    void someMethod(T sum) {
      cout << sum(1, 3) << endl;
    } 
};

SomeClass someClass;
// the template type is not required here, but has been added just for clarity.
someClass.someMethod<int(int, int)>([](int a, int b){return a + b;});

相关问题