如果我有一个模板类:
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;
};
关于c++ - 根据模板参数选择成员类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43418393/