我想创建一些带有virtual operator()作为抽象接口的模板,而不是委托其他一些带有兼容签名的类方法作为该接口的实例:
#include <type_traits>
template <typename rv_t, typename ... args_t>
struct IVirtualFunctionTemplate
{
typedef rv_t (fsignature)(args_t ...);
virtual rv_t operator()(args_t ...) = 0;
};
template<typename VF, typename rv_t, typename ... args_t>
struct SomeImpl :
public VF
{
static_assert(std::is_same<typename VF::fsignature, rv_t (args_t...)>::value, "Fail");
template <class T>
SomeImpl(T* t, rv_t (T::*method)(args_t...))
{
}
rv_t operator()(args_t ... args) override
{
//...
return rv_t();
}
};
template <typename C, typename VF, typename rv_t, typename ... args_t>
void creator(VF *& delegate, C* that, rv_t (C::*method)(args_t...))
{
delegate = new SomeImpl<VF, rv_t, args_t...>(that, method);
}
现在,我可以像这样使用它:
struct ITest :
public IVirtualFunctionTemplate<int, int>
{
};
struct Test
{
int f(int a){ return a; }
};
int main(int, char**)
{
Test t;
ITest* delegate = nullptr;
creator(delegate, &t, &Test::f);
int r = (*delegate)(42);
return 0;
}
有没有比这更好的方法:
static_assert(std::is_same<typename VF::fsignature, rv_t (args_t...)>::value, "Fail");
检查功能签名是否兼容?