作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我不确定这是否可以实现。假设我有两个类模板 Foo<T>
和 FooOwner<T>
, 和一个 FooOwner<T>
有一个指向 Foo<U>
的指针成员, 其中U
是 T
的子类.
我想制作FooOwner<T>
Foo<U>
的 friend , 但前提是 U
是 T
的子类.那可能吗?如果不是,是否有足够接近的解决方法?
template<typename T>
class FooOwner {
private:
Foo<T>* p; // This can point to a object of type Foo<U>
// where U is a subclass of T
};
// NOTE: Foo<Derived> is always a subclass of Foo<Base>
template<typename T>
class Foo {
private:
template<typename U> // Constrain U to be a superclass of T?
friend class FooOwner;
};
最佳答案
我不确定你想要实现什么,但也许是类型特征 is_base_of可以帮助你:
#include <type_traits>
class A {};
class B : A {};
class C {};
int main()
{
std::is_base_of<A, B>::value; // true
std::is_base_of<C, B>::value; // false
}
您可以将它与 conditional 一起使用:
std::conditional<std::is_base_of<A, B>::value, A, SomethingElse>::type
// will be A if B is derived from A, or SomethingElse otherwise
或用enable_if :
std::enable_if<std::is_base_of<A, B>::value, A>::type
// will be defined only if B is derived from A
关于c++ - 基于继承关系的模板友情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38539430/
标准库提供了许多有用的“is”类型特征来说明两个类的关系,例如is_base_of、is_convertible、is_same等等。有什么方法可以实现类型特征 is_friend 来判断类 A 是否
我是一名优秀的程序员,十分优秀!