[英]How to get the namespace of a template class?
I want to write a template class like:我想写一个模板 class 像:
template<class A>
class B{/*class B code*/};
there are class A is in various namespaces like:有 class A 位于各种命名空间中,例如:
namespace ns1{
class X{/*class X code*/};
class A{/*class A code*/};
}
namespace ns2{
class X{/*class X code*/};
class A{/*class A code*/};
}
Now how to access class X in the same namespace as A somewhere inside B?现在如何在与 B 内某处的 A 相同的命名空间中访问 class X?
Now how to access class X in the same namespace as A somewhere inside B?
现在如何在与 B 内某处的 A 相同的命名空间中访问 class X?
You don't.你没有。 There's no way to take a type, extract its namespace, and build a new typename by combining that namespace and a name.
没有办法获取一个类型,提取它的名称空间,并通过组合该名称空间和名称来构建一个新的类型名称。
If you need the B
template to be able to access some class that is associated with a type given by the template parameter, then that association ought to be explicit , a part of the interface of the type in some way, not based on arbitrary naming conventions.如果您需要
B
模板能够访问与模板参数给定的类型相关联的某些 class,那么该关联应该是显式的,以某种方式是该类型接口的一部分,而不是基于任意命名公约。
The two traditional mechanisms to specify this sort of thing are a member type alias or a traits class:指定此类事物的两种传统机制是成员类型别名或特征 class:
//Member alias
template<class A>
class B{
/* typename A::X is required to be an alias for the class associated with `A`.
};
namespace ns1{
class U{/*class U code*/};
class A{ using X = U;};
}
//traits
//Default implementation
template<class A>
class A_traits
{
using X = typename A::X; //By default, assume that `A` provides a member typedef.
};
template<class A>
class B{
/* typename A_traits<A>::X is required to be an alias for the class associated with `A`.
};
namespace ns1{
class U{/*class U code*/};
class A{}; //Doesn't provide the default.
}
//Specialization for `ns1::A`. Must be declared in the same namespace as the primary `A_traits` namespace
template<>
class A_traits<ns1::A>
{
using X == ns1::U;
};
The traits mechanism is more complicated, but it works with types that you don't control as well as fundamental types like int
and pointers.特征机制更复杂,但它适用于您无法控制的类型以及
int
和指针等基本类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.