模板代理方法无法编译

时间:2017-08-25 12:43:06

标签: c++ c++11 templates variadic-templates

我无法编译以下代码。

template<typename W, typename I, typename B>
class ConcreteInterfaceWrapper
{
protected:
    template<typename... Args, void (W::*Functor)( Args... )>
    static void proxyCall( void* object, Args... args ) { (static_cast<W*>( object )->Functor)( args... ); }
{

class Plugin: public ConcreteInterfaceWrapper<Plugin, IPlugin, IPluginBase>
{
public:
    void tearDown() {}
    void somethingOther() { proxyCall<&tearDown>( nullptr ); }
}

基本上我试图实现一个通用代理函数,让我可以调用派生类的成员。我使用代理函数插入C结构的函数指针,因此proxyCall的签名无法更改。另一种方法是为void proxyInitialize( void* object ) { static_cast<Derived1*>( object )->initialize(); }

等每种方法创建代理函数

我遇到了我的编译器问题(g ++)抱怨proxyCall没有匹配函数,我得到两个没用的注释:

note: candidate: template<class ... Args, void (Plugin::* Functor)(Args ...)> static void ConcreteInterfaceWrapper<W, I, B>::proxyCall(void*, Args ...) [with Args = {Args ...}; void (W::* Functor)(Args ...) = Functor; W = Plugin; I = IPlugin; B = IPluginBase]
  static void proxyCall( void*, Args... );

note:   template argument deduction/substitution failed:

1 个答案:

答案 0 :(得分:2)

编译器无法在您的情况下推断出Args...。这是一种可能的解决方法:明确传递&tearDown的类型。

template <typename F, F FPtr, typename ...Args>
static void proxyCall( void* object, Args... args ) 
{ 
    (static_cast<W*>( object )->FPtr)( args... ); 
}

void somethingOther() 
{ 
    proxyCall<decltype(&tearDown), &tearDown>( nullptr ); 
}

请注意,在C ++ 17中,您将能够:

template <auto FPtr, typename ...Args>
static void proxyCall( void* object, Args... args ) 
{ 
    (static_cast<W*>( object )->FPtr)( args... ); 
}

void somethingOther() 
{ 
    proxyCall<&tearDown>( nullptr ); 
}