如果我有一个模板类:
template<int N>
class C{
Something _x;
}
Run Code Online (Sandbox Code Playgroud)
我想_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;
};
Run Code Online (Sandbox Code Playgroud)
这可能吗?
是的。这也不是太难。
template<int N>
class C{
typename c_member<N>::type _x;
}
Run Code Online (Sandbox Code Playgroud)
在哪里
struct A {};
struct B {};
template <int N> struct c_member
{
using type = B;
};
template <> struct c_member<0>
{
using type = A;
};
Run Code Online (Sandbox Code Playgroud)
c_member如果您愿意,您可以添加更多专业。