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

标签 c++ templates

如果我有一个模板类:

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/

相关文章:

c++ - 需要关于多重继承和可选函数覆盖 C++ 的建议

templates - 如何在 D 中使用 "Template Constructors"?

c++ - 在整个系统中使用 std::chrono::steady_clock 时间是否正确?

c++ - 为什么 cout.tellp 总是返回 -1?

c++ - 为什么我不能将 unique_ptr 推回 vector 中?

c# - ZMQ消息传递特定端点

c++ - 带有模板参数的构造函数

c++ - 我可以要求编译器禁止定义模板类成员函数的泛型版本吗?

基于动态选择类型的 C++ 模板用法

c++ - C/C++ : is it possible to pass binary data through the console?