继承在类

时间:2018-05-07 18:04:15

标签: c++ c++11 templates operator-overloading

在这个最小的例子中,我有一个类A,其中定义了一个运算符+

template<class T> class A {};

template<class T1, class T2> void operator+(A<T1> a, A<T2> b) {}

template<class T> class B : public A<T> {};

int main(int, char**) {
    B<int> a, b;
    a + b;
    return 0;
}

我尝试创建从BA的隐式转换,但它要求operator+friend A并定义在A内部,当A<...>的多个实例被实例化时会导致问题。

那么,有没有其他方法可以做到这一点而无需再次定义operator+

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

const fs = require("fs");
async function test() {
    await new Promise((resolve, reject) => {
        let fss = fs.createWriteStream("file.txt", { flags: 'a+' });
        fss.write("bla");
        fss.end(() => {
            fss.destroy();
            resolve();
        });
    });
}
await test();
let val = fs.readFileSync('file.txt', 'utf8');
// do stuff here with val
这是有效的。 template<class T> class A { template<class T2> friend void operator+(A const& lhs, A<T2> const& rhs) {} }; template<class T> class B : public A<T> {}; int main(int, char**) { B<int> a, b; a + b; return 0; } 中的不对称(一个模板,一个不是)确保多个+与他们的A发生冲突。

在某些情况下,你真的需要lhs成为+的实例:

B

使用template<class T> struct A { template<class D, class T2, std::enable_if_t<std::is_base_of<A, D>{}, bool> =true > friend void operator+(D const& lhs, A<T2> const& rhs) { std::cout << D::name() << "\n"; } static std::string name() { return "A"; } }; template<class T> struct B : public A<T> { static std::string name() { return "B"; } }; int main(int, char**) { B<int> a, b; a + b; return 0; } &#39; s A,但LHS的类型为operator+。在右侧为B执行此操作并不可行,这很荒谬。