C++ 让模板通过指定位大小在char/short/int之间进行选择?
我有这样的想法:C++ 让模板通过指定位大小在char/short/int之间进行选择?,c++,templates,C++,Templates,我有这样的想法: template<int SIZE> struct bin { private: public: struct { int _value : SIZE; }; } 模板 结构箱{ 私人: 公众: 结构{ int_值:大小; }; } 是否可以根据大小更改_值的数据类型?如果尺寸=8且这不是特别优雅,但是: template <unsigned int N> struct best_integer_type {
template<int SIZE>
struct bin {
private:
public:
struct {
int _value : SIZE;
};
}
模板
结构箱{
私人:
公众:
结构{
int_值:大小;
};
}
是否可以根据大小更改_值的数据类型?如果尺寸=8且这不是特别优雅,但是:
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
};
模板
结构最佳整数类型{
typedef best_integer_type::type type;
};
模板
结构最佳整数类型{
typedef字符类型;
};
模板
结构最佳整数类型{
typedef短型;
};
模板
结构最佳整数类型{
typedef int类型;
};
模板
结构最佳整数类型{
//完全省略“type”,以引起错误
};
然后在你们班上:
typename best_integer_type<SIZE>::type _value;
typename最佳\整数\类型::类型\值;
它不处理SIZE
的负数。您的原始代码也没有,但您的文本描述中说,如果SIZEBoost.Integer具有以下功能,则使用char
:
boost::int\u t::least
最小的内置有符号整数类型,至少有N位,包括符号位。参数应为正数。如果参数大于最大整数类型中的位数,则会导致编译时错误
boost::int\u t::fast
最容易操作的内置有符号整数类型,至少有N位,包括符号位。参数应为正数。如果参数大于最大整数类型中的位数,则会导致编译时错误
谢谢,那正是我想要的。比我预期的要好。在某些时候,您可能会担心编译速度。@edA-qa-mort-ora-y:和编译内存使用,实现通常会为模板实例化施加固定的最大“递归深度”。如果我们写bin b代码>那么可能会发生一些不愉快的事情。但是,假设我们只使用合理的数字,那么编译器将只需要创建最多31个类型(每个TU),除非在人为的示例中,否则IMO不太可能成为一个巨大的负担。我认为有一些标准模板会带来更严重的几个数量级的开销。另一种方法是,代表TMP函数的模板会被自动记忆——一旦为给定的TU创建了实例化,编译器可以在再次使用结果时重新使用它。@Matthieu:只是缺少Boost.Coffee?:)