【发布时间】:2020-05-24 21:15:02
【问题描述】:
问题
拥有一个为任意成员函数生成包装器的模板,允许在对象上调用该函数,例如:
给定bool std::string::empty(),要生成的包装器将是bool wrapper(const std::string& str) { return str.empty(); }。
包装函数不能是 lambda(以便它可以作为函数指针传递)。
我的方法(对于非常量成员函数)
/* Wrapper (for non-const member functions) */
template<typename T, typename R, typename... ARGS>
struct staticWrapperHelper
{
using fType = R (T::*)(ARGS...);
template<fType FUNCTION>
static R wrapper(T& object, ARGS... args) { return object.*FUNCTION(args...); }
};
template<typename T, typename R, typename... ARGS>
auto staticWrapper(R (T::*memberFunction)(ARGS...))
{
//auto function = [memberFunction] (T& object, ARGS... args) -> R { return (object.*memberFunction)(args...); };
using Helper = staticWrapperHelper<T, R, ARGS...>;
R (*wrapper)(T&, ARGS...) = &Helper::template wrapper<R (T::*)(ARGS...)>;
return wrapper;
}
/* Example */
class A
{
public:
void member() {}
};
int main()
{
A a;
auto f = staticWrapper<A>(&A::member);
f(a);
return 0;
}
我的方法有问题
它不会编译。看起来返回的包装器仍然是一个模板:http://coliru.stacked-crooked.com/a/d4c0dd9ab631aa1f
g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out main.cpp: 在 'auto staticWrapper(R (T::*)(ARGS ...)) [with T = A; R = 无效; ARGS = {}]': main.cpp:32:41:从这里需要 main.cpp:17:9: 错误: 没有匹配转换函数'wrapper'到类型'void (*)(class A&)' 17 | R (*wrapper)(T&, ARGS...) = &Helper::template wrapper; | ^~~~~~~ main.cpp:8:14:注意:候选是:'template static R staticWrapperHelper::wrapper(T&, ARGS ...) [with R (T::* FUNCTION)(ARGS ...) = FUNCTION; T = A; R = 无效; ARGS = {}]' 8 |静态 R 包装器(T& 对象,ARGS... args){ 返回对象。*FUNCTION(args...); } | ^~~~~~~有什么想法吗?
【问题讨论】:
标签: c++ c++14 metaprogramming function-pointers pointer-to-member