如何为其他类成员函数编写模板包装器方法? [英] How to write a template wrapper method for other class member functions?
本文介绍了如何为其他类成员函数编写模板包装器方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试为具有不同参数的不同功能创建模板包装器。
设置是 A
类,具有两个方法 foo
和栏
。另一个类 B
将包装这些方法并添加新功能。
I try to create a templated wrapper for different functions with different parameters.
The setup is a class A
with the basic implementation of two methods foo
and bar
. Another class B
shall wrap these methods and add new functionality.
以下链接中的解决方案对于非类函数非常适用:
c ++ 11:模板化包装函数
The solution from the following link works very well for non-class functions: c++11: Templated wrapper function
但是如果我尝试从另一个类调用方法,我会得到一个
But if I try to invoke methods from another class I get an error.
#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
See this link for more details std::mem_fn
这篇关于如何为其他类成员函数编写模板包装器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文