gpt4 book ai didi

c++ - 是否可以在 C++11 中创建每个实例的 mixin?

转载 作者:IT老高 更新时间:2023-10-28 22:23:42 30 4
gpt4 key购买 nike

是否可以在 C++ (C++11) 中创建 mixins - 我想为每个实例而不是每个类创建行为。

在 Scala 中,我会使用匿名类来做到这一点

val dylan = new Person with Singer

最佳答案

如果这些是您现有的类(class):

class Person
{
public:
Person(const string& name): name_(name) {}
void name() { cout << "name: " << name_ << endl; }

protected:
string name_;
};

class Singer
{
public:
Singer(const string& song, int year): song_(song), year_(year) {}
void song() { cout << "song: " << song_ << ", " << year_ << endl; }

protected:
string song_;
int year_;
};

然后你可以在 C++11 中玩转这个概念

template<typename... Mixins>
class Mixer: public Mixins...
{
public:
Mixer(const Mixins&... mixins): Mixins(mixins)... {}
};

像这样使用它:

int main() {    
Mixer<Person,Singer> dylan{{"Dylan"} , {"Like a Rolling Stone", 1965}};

dylan.name();
dylan.song();
}

关于c++ - 是否可以在 C++11 中创建每个实例的 mixin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17628534/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com