c++ Mixins——这是正确的实现方式吗?

C++ Mixins - Is this the correct way of implementing?

本文关键字:实现 方式吗 Mixins c++      更新时间:2023-10-16

大家好,我已经创建了一个mixin类(超级设计),用于打印元素T(某种类型T),它有一个名为name()的方法。

我想知道这是否被认为是在c++中实现的正确方法?

欢迎发表意见。

template<class T>
struct name_method_printer_to_console_mixin{
    void print() const{
        auto& that = static_cast<T const&>(*this);
        cout << "Mixin printing name which is: " << that.name() << endl;
    }
};
class customer : public name_method_printer_to_console_mixin<customer>{
public:
    customer(){}
    customer(string const &name) : name_(name){}
    string const & name() const{
        return name_;
    }
private:
    string name_;
};
布莱尔

看起来有效。我不确定它是否有用,但这是超级人造课程的标准。

我建议转换指针并使用->name()而不是引用。它们做同样的事情,但是指针更容易理解