【发布时间】:2018-12-11 14:08:08
【问题描述】:
(1) 如何创建函数的 std::vector 以便可以执行以下操作:
int main ()
{
std::vector<????> vector_of_functions;
// Add an adding function into the vector
vector_of_functions.push_back(
double function (double a, double b) {
return a + b
}
);
// Add a multiplying function into the vector
vector_of_functions.push_back(
double function (double a, double b) {
return a * b;
}
);
// Use the functions
std::cout << "5 + 7 = " << vector_of_functions[0](5, 7); // >>> 5 + 7 = 12
std::cout << "5 * 7 = " << vector_of_functions[1](5, 7); // >>> 5 * 7 = 35
return 0;
}
虽然我希望函数返回和参数可以是任何类型,但不一定非要如此。如果他们是固定类型,我很好。
(2) 如何将那种 std::vector 作为函数的参数传递。
void func (std::vector<???> vof) {
std::cout << vof[0](5, 7);
};
int main ()
{
std::vector<????> vector_of_functions;
// Add an adding function into the vector
vector_of_functions.push_back(
double function (double a, double b) {
return a + b
}
);
// Add a multiplying function into the vector
vector_of_functions.push_back(
double function (double a, double b) {
return a * b;
}
);
// Call the function
func( vector_of_functions ); // >>> 12
return 0;
}
(3) 除了函数是头文件中定义的类的方法外,我该如何做同样的事情。
.cpp 代码与之前相同,除了函数为void ClassName::func(...);
.h 代码将是这样的:
class ClassName {
public:
ClassName();
void func(????);
}
【问题讨论】:
-
看看
std::function和std::bind -
使用lambdas 和
std::function,卢克!
标签: c++ function class pointers stdvector