C++:如何要求一种模板类型派生自另一种模板类型 [英] C++: How to require that one template type is derived from the other

查看:37
本文介绍了C++:如何要求一种模板类型派生自另一种模板类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在比较运算符中:

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++:如何要求一种模板类型派生自另一种模板类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆