繁体   English   中英

根据模板参数选择成员类型?

[英]Choose member type based on template arguments?

如果我有模板类:

template<int N>
class C{
    Something _x;
}

我想根据N的值来控制类成员_x的类型。 假设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;
};

唯一的优点是您拥有了重载解析的全部功能来选择类型,并且您不必弄乱模板的专业化,也不必使一个复杂的条件涵盖很多情况。

如果您使用简单的逻辑在两种类型之间进行选择,那就太过分了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM