我不确定这是否可以实现。假设我有两个类模板 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/