c++ - 让模板通过指定 bitesize 在 char/short/int 之间进行选择?

标签 c++ templates

我有这样的东西:

template<int SIZE>
struct bin {
private:
public:
    struct {
        int _value : SIZE;
    };
}

是否可以根据 SIZE 更改 _value 的数据类型?如果 SIZE <= 7,我希望 _value 是一个字符。如果它 >= 8 且 <= 15,我希望它很短,如果它 <= 31,我希望它是一个整数。

最佳答案

这不是特别优雅,但是:

template <unsigned int N>
struct best_integer_type {
    typedef best_integer_type<N-1>::type type;
};

template <>
struct best_integer_type<0> {
    typedef char type;
};

template <>
struct best_integer_type<8> {
    typedef short type;
};

template <>
struct best_integer_type<16> {
    typedef int type;
};

template <>
struct best_integer_type<32> {
    // leave out "type" entirely, to provoke errors
};

然后在你的类里面:

typename best_integer_type<SIZE>::type _value;

它不处理 SIZE 的负数.您的原始代码也没有,但您的文字描述说使用 char如果SIZE <= 7 .我期待 0 <= SIZE <= 7会做的。

关于c++ - 让模板通过指定 bitesize 在 char/short/int 之间进行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9095303/

相关文章:

c++ - 我是否需要在 CUDA 中跨多个 GPU 镜像输入缓冲区/纹理?

c++ - 模板参数推导失败

c++ - 非类型模板参数可以实现哪些优化?

c++ - 通过字符串模板参数访问元组

c++ - 单个 MFC/Win32 控件似乎让我的整个桌面重绘

c++ - : returnType vs returnType &?这几种形式有区别吗

c++ - Ideone和Codepad真的不支持C++03吗?

c++ - 将 uint64_t 转换为字节时从不同大小的整数转换为指针

c++ - 多个可变参数模板函数

c++ - 如何检查嵌套模板的类型?