問題描述
在比較運算符中:
template<class R1, class R2>
bool operator==(Manager<R1> m1, Manager<R2> m2) {
return m1.internal_field == m2.internal_field;
}
有什么辦法可以強制 R1 和 R2 必須具有超類型或子類型關系?也就是說,我想允許 R1 派生自 R2,或 R2 派生自 R1,但如果 R??1 和 R2 是不相關的類型,則不允許進行比較.
Is there any way I could enforce that R1 and R2 must have a supertype or subtype relation? That is, I'd like to allow either R1 to be derived from R2, or R2 to be derived from R1, but disallow the comparison if R1 and R2 are unrelated types.
推薦答案
您想要的特征可能如下所示:
A trait you want might look like this:
template <typename B, typename D>
struct is_base_of // check if B is a base of D
{
typedef char yes[1];
typedef char no[2];
static yes& test(B*);
static no& test(...);
static D* get(void);
static const bool value = sizeof(test(get()) == sizeof(yes);
};
那么你只需要某種靜態斷言:
Then you just need a static assert of some sort:
// really basic
template <bool>
struct static_assert;
template <>
struct static_assert<true> {}; // only true is defined
#define STATIC_ASSERT(x) static_assert<(x)>()
然后將兩者放在一起:
template<class R1, class R2>
bool operator==(Manager<R1> m1, Manager<R2> m2)
{
STATIC_ASSERT(is_base_of<R1, R2>::value || is_base_of<R2, R1>::value);
return p1.internal_field == p2.internal_field;
}
如果一個不派生自另一個,該函數將不會編譯.(您的錯誤將類似于static_assert
not defined",它將指向該行.)
If one does not derive from the other, the function will not compile. (Your error will be similar to "static_assert<false>
not defined", and it will point to that line.)
這篇關于C++:如何要求一種模板類型派生自另一種模板類型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!