使用基类中的函数作为派生类中的模板

时间:2017-09-22 10:14:50

标签: c++ templates

这是我的用例:

class A:
protected: 
   virtual void methodA1(const void* const s, const std::streamsize n) const;
   inline void methodA2(const void* const s, const std::streamsize n) const;

class B : public A
private:
    const  char *a;
    template <void (*T)(const void* const, const std::streamsize)>
    void doOperation(const char* b) {        
        T(a, b - a);
    }

    //here comes the template usage
    void methodB1(const char *x) {
         doOperation<methodA1>(x);
    }

    void methodB2(const char *x) {
         doOperation<methodA2>(x);
    }

问题是不会编译。我收到template argument deduction/substitution failed:invalid use of non-static member function这样的错误。

我怎样才能达到预期的行为?

1 个答案:

答案 0 :(得分:2)

methodA1的类型为void (A::*)(const void* s, std::streamsize) const

因此,您必须将代码调整为:

class A
{
public:
   virtual void methodA1(const void* const s, const std::streamsize n) const = 0;
   void methodA2(const void* const s, const std::streamsize n) const {}
};

class B : public A
{
private:
    const  char *a;
    void methodA1(const void* s, std::streamsize n) const override {}

    template <void (A::*M)(const void*, std::streamsize) const>
    void doOperation(const char* b) {        
        (this->*M)(a, b - a); // method pointer usage
    }

    //here comes the template usage
    void methodB1(const char *x) {
         doOperation<&A::methodA1>(x);
    }

    void methodB2(const char *x) {
         doOperation<&A::methodA2>(x);
    }
};
相关问题