从派生模板类覆盖纯虚函数

Mic*_*l W 2 c++ inheritance templates

有谁知道为什么这段代码无法在visual studio 2013中编译?问题在于ba()只有一个版本(B类a(float)中的覆盖版本)和版本a(std :: string)不可用,尽管它在基类中.

#include <string>

template <typename T>
class A { 
public:
    virtual void a(std::string b){ this->a(123); }
    virtual void a(float b) = 0;
};

class B : public A < std::string > {
public:
    virtual void a(float b) override {}
};


main()
{
    B b;

    b.a(""); // Error here: error C2664: 
             // 'void B::a(float)' : cannot convert argument 1 from 'const char [1]' to 'float'

    B* bb = new B();
    bb->a(""); // same
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 5

如果派生类声明了一个名称,并且您还希望基类中的此名称成员可见,则需要使用using以下方法显式取消隐藏这些名称:

class B : public A<std::string>
{
public:
    using A<std::string>::a;
    virtual void a(float b) override {}
};
Run Code Online (Sandbox Code Playgroud)

现在您可以使用以下所有重载a:

B x;
x.a(1.2);
x.a("hello");
Run Code Online (Sandbox Code Playgroud)