在派生类中重载模板运算符[重复]

问题描述 投票:5回答:1

给定基类和派生类,它们都使用SFINAE为特定参数类型提供有条件启用的运算符:

#include <type_traits>

class Base
{
public:
    template<class T, std::enable_if_t<std::is_scalar_v<T>>* = nullptr>
    void operator>>(T& value) {
    }
};

class Derived: public Base
{
public:
    using Base::operator>>;

    template<class T, std::enable_if_t<!std::is_scalar_v<T>>* = nullptr>
    void operator>>(T& value) {
    }
};


int main(int argc, char *argv[])
{
    int foo;

    Base base;
    base >> foo; // this works

    Derived derived;
    derived >> foo; // this doesn't work, the operator from the base class is not considered
}

然后在派生类的实例上调用基类中定义的运算符将不起作用,即使它应该通过适当的using Base::operator>>;声明可见。为什么?如何在不详细重复声明/定义的情况下使基类中的运算符可用?

如果有问题的运算符不是基类中的模板,则不会发生此问题。

编辑:使用msvc 15.9.7以及clang进行测试。

c++ templates operator-overloading c++17 sfinae
1个回答
2
投票

我认为这里的问题是using声明只将函数和函数模板的声明带入一个派生类,该派生类的签名不会被派生类[namespace.udecl]/15的成员覆盖。所以这段代码确实不应该编译。

使用自由函数而不是类成员来解决问题:

#include <type_traits>

class Base
{
public:
    template<class T, std::enable_if_t<std::is_scalar_v<T>>* = nullptr>
    friend void operator>>(Base&, T& value) {
    }
};

class Derived: public Base
{
public:
    template<class T, std::enable_if_t<!std::is_scalar_v<T>>* = nullptr>
    friend void operator>>(Derived&, T& value) {
    }
};

int main()
{
    int foo;

    Base base;
    base >> foo;

    Derived derived;
    derived >> foo;
}

live example here

© www.soinside.com 2019 - 2024. All rights reserved.