本篇内容介绍了“C++怎么结合使用泛型和面向对象技术”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
T.5:结合使用泛型和面向对象技术应该增强它们的效果而不是成本
Generic and OO techniques are complementary.
泛型和面向对象技术是互补的。
Example(示例)
Static helps dynamic: Use static polymorphism to implement dynamically polymorphic interfaces.
静态协助动态:使用静态多态技术实现动态多态接口。
class Command {
// pure virtual functions
};
// implementations
template</*...*/>
class ConcreteCommand : public Command {
// implement virtuals
};
Dynamic helps static: Offer a generic, comfortable, statically bound interface, but internally dispatch dynamically, so you offer a uniform object layout. Examples include type erasure as with std::shared_ptr's deleter (but don't overuse type erasure).
动态帮助静态:提供通用,舒适的静态边界的接口,但是内部进行动态分发,这样就可以提供一致的对象布局。示例代码引入了和std::shared_ptr的删除器一样的类型消除机制。
#include <memory>
class Object {
public:
template<typename T>
Object(T&& obj)
: concept_(std::make_shared<ConcreteCommand<T>>(std::forward<T>(obj))) {}
int get_id() const { return concept_->get_id(); }
private:
struct Command {
virtual ~Command() {}
virtual int get_id() const = 0;
};
template<typename T>
struct ConcreteCommand final : Command {
ConcreteCommand(T&& obj) noexcept : object_(std::forward<T>(obj)) {}
int get_id() const final { return object_.get_id(); }
private:
T object_;
};
std::shared_ptr<Command> concept_;
};
class Bar {
public:
int get_id() const { return 1; }
};
struct Foo {
public:
int get_id() const { return 2; }
};
Object o(Bar{});
Object o2(Foo{});
In a class template, non-virtual functions are only instantiated if they're used -- but virtual functions are instantiated every time. This can bloat code size, and may overconstrain a generic type by instantiating functionality that is never needed. Avoid this, even though the standard-library facets made this mistake.
在类模板中,非虚函数只有在被使用时才会实例化-但是虚函数任何时候都会实例化。这会使代码膨胀,并且因为实例化根本不用的功能而过度约束通用类型。要避免这个问题,即使标准库有时也会犯这样的错误。
Enforcement(实施建议)
See the reference to more specific rules.
参见更加具体的规则。
“C++怎么结合使用泛型和面向对象技术”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。