我尝试为具有不同参数的不同功能创建模板包装器。该设置是一类,A
具有两个方法foo
和的基本实现bar
。另一个类B
应包装这些方法并添加新功能。
以下链接中的解决方案非常适用于非类函数:c ++ 11:模板化包装器函数
但是,如果我尝试从另一个类调用方法,则会收到错误消息。
#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)
]
任何想法如何解决这个问题?
尝试这个,
#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, x);
}
void barAndMore(int x, float y) {
foobarWrapper(&A::bar, x, y);
}
template<typename T, typename... Args>
void foobarWrapper(T func, Args&&... args)
{
std::cout << "Start!" << std::endl;
auto caller = std::mem_fn( func); // Newly added lines
caller( A(), args...); // Newly added line
std::cout << "End!" << std::endl;
}
};
int main()
{
B b;
b.fooAndMore(1);
b.barAndMore(2, 3.5f);
}
输出:
Start!
Foo: 1
End!
Start!
Bar: 2, 3.5
End!
有关更多详细信息,请参见此链接std :: mem_fn
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句