您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“C++怎么結(jié)合使用泛型和面向?qū)ο蠹夹g(shù)”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!
T.5:結(jié)合使用泛型和面向?qū)ο蠹夹g(shù)應該增強它們的效果而不是成本
Generic and OO techniques are complementary.
泛型和面向?qū)ο蠹夹g(shù)是互補的。
Example(示例)
Static helps dynamic: Use static polymorphism to implement dynamically polymorphic interfaces.
靜態(tài)協(xié)助動態(tài):使用靜態(tài)多態(tài)技術(shù)實現(xiàn)動態(tài)多態(tài)接口。
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).
動態(tài)幫助靜態(tài):提供通用,舒適的靜態(tài)邊界的接口,但是內(nèi)部進行動態(tài)分發(fā),這樣就可以提供一致的對象布局。示例代碼引入了和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.
在類模板中,非虛函數(shù)只有在被使用時才會實例化-但是虛函數(shù)任何時候都會實例化。這會使代碼膨脹,并且因為實例化根本不用的功能而過度約束通用類型。要避免這個問題,即使標準庫有時也會犯這樣的錯誤。
Enforcement(實施建議)
See the reference to more specific rules.
參見更加具體的規(guī)則。
“C++怎么結(jié)合使用泛型和面向?qū)ο蠹夹g(shù)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。