C++备忘录022:CRTP和mixin

mac2025-06-11  34

CRTP(curiously repeating template pattern)虽然使用继承,但是它表现的不是```is-a``的关系,而是对接口的扩展

template <typename T> struct Par { std::string add() { T &t{static_cast<T&>(*this)}; return "[" + t.name() + "]"; } }; struct Name : public Par<Name> { std::string name() { return "hello"; } }; int main() { std::cout << Par<Name>{}.add() << '\n'; }

mixin与CRTP相反,它保持原类不变,接口类继承原类

template <typename T> struct Par : T { std::string add() { return "[" + this->name() + "]"; } }; struct Name { std::string name() { return "hello"; } }
最新回复(0)