有沒有辦法來定義模板C++中的模板斷言?
assertInheritsFrom<A, B>
這樣
assertsInheritsFrom<A, B>
編譯當且僅當
class A : public B { ... } // struct A is okay too
謝謝!
有沒有辦法來定義模板C++中的模板斷言?
assertInheritsFrom<A, B>
這樣
assertsInheritsFrom<A, B>
編譯當且僅當
class A : public B { ... } // struct A is okay too
謝謝!
您可以從Alexandrescu的書中閱讀此部分Detecting convertibility and inheritance at compile time。
編輯:還有一個鏈接一樣:http://www.ddj.com/cpp/184403750查找檢測兌換和繼承
您能否在此提供摘要? Google只會經常提供一本書,然後暫時阻止其他人。 – 2010-01-28 06:43:47
實現它;作品完美無瑕。 – anon 2010-01-28 10:38:56
結合靜態與is_base_of<Base,Derived>
斷言從Boost.TypeTraits:
BOOST_STATIC_ASSERT(boost::is_base_of<B, A>::value);
一個天真的實現(不照顧整型,私人基類和歧義)可能看起來像下面這樣:
template<class B, class D>
struct is_base_of {
static yes test(const B&); // will be chosen if B is base of D
static no test(...); // will be chosen otherwise
static const D& helper();
static const bool value =
sizeof(test(helper())) == sizeof(yes);
// true if test(const B&) was chosen
};
你能解釋一下這是如何工作的嗎? (即如何實現is_base_of,這有點超出我的理解) – anon 2010-01-28 04:53:57
它是一個開源庫:http://www.boost.org/doc/libs/1_41_0/libs/type_traits/doc/html/boost_typetraits/reference/ is_base_of.html – 2010-01-28 06:44:58
特拉維斯,這是從答案相同的鏈接,並沒有真正解釋它是如何工作的。檢查代碼也不一定能解釋它。有時散文有幫助。但可能不是適合Stack Overflow評論的數量。匿名,如果你試圖閱讀代碼,但仍然不明白,請發佈一個關於它的新問題。 (請注意,在Boost的is_base_and_derived.hpp中有一些解釋,並帶有一些鏈接。) – 2010-01-28 06:58:53
您可能還需要閱讀從Bjarne的Stroustrup的C++ FAQ此項:Why can't I define constraints for my template parameters?(答案是,你可以,他提供了一個示例,說明如何實現約束。)
附註:*模板*(帶有拖尾的s)是更常用的標籤。 – 2010-01-28 04:53:52
好的;公認。不會回滾。 – anon 2010-01-28 05:01:11