RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
C++怎么结合使用泛型和面向对象技术

本篇内容介绍了“C++怎么结合使用泛型和面向对象技术”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

成都创新互联公司专注于企业营销型网站建设、网站重做改版、喀左网站定制设计、自适应品牌网站建设、H5高端网站建设成都商城网站开发、集团公司官网建设、外贸网站制作、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为喀左等各大城市提供网站开发制作服务。

T.5:结合使用泛型和面向对象技术应该增强它们的效果而不是成本

Reason(原因)

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
};
Example(示例)

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 

class Object {
public:
   template
   Object(T&& obj)
       : concept_(std::make_shared>(std::forward(obj))) {}

   int get_id() const { return concept_->get_id(); }

private:
   struct Command {
       virtual ~Command() {}
       virtual int get_id() const = 0;
   };

   template
   struct ConcreteCommand final : Command {
       ConcreteCommand(T&& obj) noexcept : object_(std::forward(obj)) {}
       int get_id() const final { return object_.get_id(); }

   private:
       T object_;
   };

   std::shared_ptr 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{});
Note(注意)

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++怎么结合使用泛型和面向对象技术”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


文章题目:C++怎么结合使用泛型和面向对象技术
网址分享:http://scyingshan.cn/article/jjidod.html