我是否更喜欢使用mixins或函数模板向一组不相关的类型添加行为?

Luc*_*lle 4 c++ oop templates mixins

Mixins和函数模板是为多种类型提供行为的两种不同方式,只要这些类型满足某些要求即可.

例如,假设我想编写一些允许我将对象保存到文件的代码,只要这个对象提供了一个toString成员函数(这是一个相当愚蠢的例子,但请耐心等待).第一种解决方案是编写如下函数模板:

template <typename T>
void toFile(T const & obj, std::string const & filename)
{
    std::ofstream file(filename);
    file << obj.toString() << '\n';
}
...
SomeClass o1;
toFile(o1, "foo.txt");
SomeOtherType o2;
toFile(o2, "bar.txt");
Run Code Online (Sandbox Code Playgroud)

另一个解决方案是使用CRTP使用mixin :

template <typename Derived>
struct ToFile
{
    void toFile(std::string const & filename) const
    {
        Derived * that = static_cast<Derived const *>(this);
        std::ofstream file(filename);
        file << that->toString() << '\n';
    }
};

struct SomeClass : public ToFile<SomeClass>
{
    void toString() const {...}
};
...
SomeClass o1;
o.toFile("foo.txt");
SomeOtherType o2;
o2.toFile("bar.txt");
Run Code Online (Sandbox Code Playgroud)

这两种方法的优点和缺点是什么?是否有一个受欢迎的,如果有,为什么?

Bjö*_*lex 5

第一种方法更灵活,因为它可以使用任何类型提供任何方式转换为a std::string(这可以使用traits-classes实现),而无需修改该类型.您的第二种方法总是需要修改类型才能添加功能.