如果我有一个模板类:根据模板参数选择成员类型?
template<int N>
class C{
Something _x;
}
我想控制类成员_x
的取决于N
值的类型。如果N为0,则_x应为A型,否则_x应为B型。
这可能吗?
我不想仅仅将该类型作为模板参数传递,因为它可能违反确定要使用哪种类型的规则。例如,我可以做C<1, A>
这是不正确的。
如果我有一个模板类:根据模板参数选择成员类型?
template<int N>
class C{
Something _x;
}
我想控制类成员_x
的取决于N
值的类型。如果N为0,则_x应为A型,否则_x应为B型。
这可能吗?
我不想仅仅将该类型作为模板参数传递,因为它可能违反确定要使用哪种类型的规则。例如,我可以做C<1, A>
这是不正确的。
对于只有几种可能类型的场景,可以使用std::conditional
。
#include <type_traits>
struct A {};
struct B {};
template<int N>
class M {
public:
std::conditional_t<N == 0, A, B> _x;
};
这可能吗?
是的。这也不是太困难。
template<int N>
class C{
typename c_member<N>::type _x;
}
其中
struct A {};
struct B {};
template <int N> struct c_member
{
using type = B;
};
template <> struct c_member<0>
{
using type = A;
};
,如果你愿意,你可以添加更多的c_member
专业化。
有很多方法可以做到这一点。我喜欢做超载,asmit允许简单的扩展性。
template<int N>using int_t=std::integral_constant<int,N>;
template<class T>struct tag_t{using type=T; constexpr tag_t(){}};
template<class Tag>using type=typename Tag::type;
struct A{}; struct B{};
inline tag_t<A> something(int_t<0>){return {};}
template<int x>
inline tag_t<B> something(int_t<x>){return {};}
现在我们只:
template<int N>
class M {
public:
type<decltype(something(int_t<N>{}))> _x;
};
唯一的优势就是你得到的重载决议的全部力量来接的类型,你不必与模板特乱,而你不知道不必让一个复杂的条件覆盖很多情况。
如果你用简单的逻辑在两种类型之间进行选择,这是矫枉过正的。
我会为此与其他答案一样(因为它更简单),但谢谢! – user997112
@ user997112,不是问题。 –