c++ - 模板代理方法无法编译

标签 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:

最佳答案

编译器无法在您的情况下推断出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 ); 
}

关于c++ - 模板代理方法无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45881721/

相关文章:

c++ - 使用模板 C++ 的链表实现中未解析的外部符号

c++ - 海湾合作委员会 : C++11 inline object initialization (using "this") does not work when there is a virtual inheritance in hierarchy

c++ - `static_cast<bool>(x)` 和 `x != 0.0` 之间有区别吗?

c++ - 如果编译器符合 Cpp0x,#defined 是什么?

c++ - std::bind 与 lambda 性能

python - 使用 Python/Flask 进行 MySQL 查询

c++ - 检查变量类型是否可迭代?

c++ - 如何定义嵌套模板的静态成员(模板类内部的模板类)

c++ - 使用带有 std::shared_ptr 的 Qt 对象

c++ - 什么时候应该删除动态创建的单例对象?