我尝试为具有不同参数的不同函数创建一个模板化包装器。
设置是一个类A
基本实现有两种方法foo
and bar
。另一堂课B
应包装这些方法并添加新功能。
以下链接中的解决方案对于非类函数非常有效:c++11:模板化包装函数 https://stackoverflow.com/questions/25495448/c11-templated-wrapper-function
但是,如果我尝试从另一个类调用方法,则会收到错误。
#include <algorithm>
#include <functional>
#include <iostream>
class A
{
public:
void foo(int x) {
std::cout << "Foo: " << x << std::endl;
}
void bar(int x, float y) {
std::cout << "Bar: " << x << ", " << y << std::endl;
}
};
class B
{
public:
void fooAndMore(int x) {
foobarWrapper(&A::foo, 1);
}
void barAndMore(int x, float y) {
foobarWrapper(&A::bar, 1, 3.5f);
}
template<typename T, typename... Args>
void foobarWrapper(T&& func, Args&&... args)
{
std::cout << "Start!" << std::endl;
std::forward<T>(func)(std::forward<Args>(args)...);
std::cout << "End!" << std::endl;
}
};
int main()
{
B b;
b.fooAndMore(1);
b.barAndMore(2, 3.5f);
}
我期待这样的事情:
Start!
Foo: 1
End!
Start!
Bar: 1, 3.5
End!
但我得到的是:
error C2064: term does not evaluate to a function taking 1 arguments
note: see reference to function template instantiation 'void B::foobarWrapper<void(__thiscall A::* )(int),int>(T &&,int &&)' being compiled
with
[
T=void (__thiscall A::* )(int)
]
error C2064: term does not evaluate to a function taking 2 arguments
note: see reference to function template instantiation 'void B::foobarWrapper<void(__thiscall A::* )(int,float),int,float>(T &&,int &&,float &&)' being compiled
with
[
T=void (__thiscall A::* )(int,float)
]
知道如何解决这个问题吗?