您好,登錄后才能下訂單哦!
本篇內容介紹了“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。