我想模仿std::function
模板参数,但我不知道它是如何工作的。
例如考虑以下代码:
std::function<int(int)> p;
如何编写模仿此模板参数的类模板 <int(int)>
?
template<typename ...> <-- what should be here instead of `...`
MyClass
我真正想要实现的是我希望能够 typedef <int(int)>
作为函数指针,我希望它不仅对于 int (*func)(int)
是通用的功能。
我正在努力实现这样的目标:
SomeSmartStruct<MyClass, int(int)>::MemFuncPointerType pMemFunc;
我要MemFuncPointerType
属于以下类型:
int (__thiscall MyClass::* )(int)
还有:
SomeSmartStruct<MyClass, int(int)>::FunctionPointer pFunc;
应该是这种类型:
int (__cdecl *)(int)
我使用的是 VS2010,因此并非支持所有 C++11 功能,但它确实实现了 std::function
.
最佳答案
使用可变参数模板:
template <typename C, typename T>
struct make_member_function_pointer;
template <typename C, typename R, typename... Args>
struct make_member_function_pointer<C,R(Args...)>
{
using type = R(C::*)(Args...);
};
没有可变参数模板:
template <typename T> struct identity { typedef T type; };
template <typename C, typename T>
struct make_member_function_pointer;
template <typename C, typename R, typename Arg1>
struct make_member_function_pointer<C,R(Arg1)> : identity<R(C::*)(Arg1)> {};
template <typename C, typename R, typename Arg1, typename Arg2>
struct make_member_function_pointer<C,R(Arg1,Arg2)> : identity<R(C::*)(Arg1,Arg2)> {};
template <typename C, typename R, typename Arg1, typename Arg2, typename Arg3>
struct make_member_function_pointer<C,R(Arg1,Arg2,Arg3)> : identity<R(C::*)(Arg1,Arg2,Arg3)> {};
用法:
template <typename T, typename F>
struct SomeSmartStruct
{
typedef typename make_member_function_pointer<T,F>::type MemFuncPointerType;
typedef F* FunctionPointer;
};
测试:
struct MyClass
{
int foo(int) {return 0;}
};
int bar(int) {return 0;}
int main()
{
SomeSmartStruct<MyClass, int(int)>::MemFuncPointerType pMemFunc = &MyClass::foo;
SomeSmartStruct<MyClass, int(int)>::FunctionPointer pFunc = &bar;
}
更新
Can I somehow utilize the preprocessor to auto generate partial specializations of make_member_function_pointer? I've seen something similar is done using BOOST_PP_ITERATION but I don't know how it works.
当然:
#include <boost/preprocessor.hpp>
template <typename T> struct identity { typedef T type; };
template <typename C, typename T>
struct make_member_function_pointer;
#define BOOST_PP_LOCAL_MACRO(n)\
template <typename C, typename R BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Arg)>\
struct make_member_function_pointer<C,R(BOOST_PP_ENUM_PARAMS(n, Arg))> : identity<R(C::*)(BOOST_PP_ENUM_PARAMS(n, Arg))> {};
#define BOOST_PP_LOCAL_LIMITS (0, 20) // 20 is the limit of params
#include BOOST_PP_LOCAL_ITERATE()
测试:
int bar10(int,int,int,int,int,int,int,int,int,int) {return 0;}
SomeSmartStruct<MyClass, int(int,int,int,int,int,int,int,int,int,int)>::FunctionPointer pFunc10 = &bar10;
关于c++ - 模仿 std::function 模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27541881/