我需要将具有不同返回类型的不同方法(成员函数)分配给定义为自动变量的变量。 因此,返回相同数据类型的以下代码可以按预期工作:
#include <iostream>
// Function pointers
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
// Define a type for function pointer
using OperationFunc = int (*)(int, int);
int main() {
// Using auto with function pointers
auto operation = add;
std::cout << "Result of addition: " << operation(5, 3) << std::endl;
operation = subtract;
std::cout << "Result of subtraction: " << operation(5, 3) << std::endl;
// Using auto with lambda functions
auto multiply = [](int a, int b) { return a * b; };
std::cout << "Result of multiplication: " << multiply(5, 3) << std::endl;
return 0;
}
但是当我尝试使其更通用时,如下所示
#include <iostream>
#include <functional>
class MyClass {
public:
int add(int a, int b) {
return a + b;
}
double multiply(double a, double b) {
return a * b;
}
};
int main() {
MyClass obj;
// Assigning member functions to auto variable using std::function and lambdas
auto operation = [&obj](auto func, auto... args) {
return func(obj, args...);
};
// Using auto variable to call different member functions with different return types
std::cout << "Result of addition: " << operation(&MyClass::add, 5, 3) << std::endl;
std::cout << "Result of multiplication: " << operation(&MyClass::multiply, 5.5, 3.0) << std::endl;
return 0;
}
我收到以下错误代码。
> main.cpp: In instantiation of ‘main()::<lambda(auto:1, auto:2 ...)>
> [with auto:1 = int (MyClass::*)(int, int); auto:2 = {int, int}]’:
> main.cpp:24:53: required from here main.cpp:20:20: error: must use
> ‘.*’ or ‘->*’ to call pointer-to-member function in ‘func (...)’, e.g.
> ‘(... ->* func) (...)’ 20 | return func(obj, args...);
> | ~~~~^~~~~~~~~~~~~~ main.cpp: In instantiation of ‘main()::<lambda(auto:1, auto:2 ...)> [with auto:1 = double
> (MyClass::*)(double, double); auto:2 = {double, double}]’:
> main.cpp:25:59: required from here main.cpp:20:20: error: must use
> ‘.*’ or ‘->*’ to call pointer-to-member function in ‘func (...)’, e.g.
> ‘(... ->* func) (...)’
有什么建议或提示如何修复它吗?
您的错误不是使用不同的函数类型,而是错误地调用成员函数。
std::invoke
:
auto operation = [&obj](auto func, auto... args) {
return std::invoke(func, obj, std::forward<decltype(args)>(args)...);
};
如果你不能使用C++17,你必须使用丑陋的指针成员访问语法:
auto operation = [&obj](auto func, auto... args) {
return (obj.*func)(std::forward<decltype(args)>(args)...);
};