如何专门针对一系列整数值的C ++模板? [英] How can I specialize a C++ template for a range of integer values?
本文介绍了如何专门针对一系列整数值的C ++模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种方法可以基于一系列值而不只是一个值来进行模板专业化?我知道以下代码不是有效的C ++代码,但它显示了我想要执行的操作。我正在为8位计算机编写代码,因此使用整数和字符的速度有所不同。
Is there a way to have a template specialization based on a range of values instead of just one? I know the following code is not valid C++ code but it shows what I would like to do. I'm writing code for a 8-bit machine, so there is a difference in speed for using ints and chars.
template<unsigned SIZE>
class circular_buffer {
unsigned char buffer[SIZE];
unsigned int head; // index
unsigned int tail; // index
};
template<unsigned SIZE <= 256>
class circular_buffer {
unsigned char buffer[SIZE];
unsigned char head; // index
unsigned char tail; // index
};
推荐答案
尝试 std :: conditional :
#include <type_traits>
template<unsigned SIZE>
class circular_buffer {
typedef typename
std::conditional< SIZE < 256,
unsigned char,
unsigned int
>::type
index_type;
unsigned char buffer[SIZE];
index_type head;
index_type tail;
};
如果您的编译器尚不支持C ++ 11的这一部分,则增强库。
If your compiler doesn't yet support this part of C++11, there's equivalent in boost libraries.
然后,很容易自己动手(贷记给KerrekSB):
Then again, it's easy to roll your own (credit goes to KerrekSB):
template <bool, typename T, typename F>
struct conditional {
typedef T type;
};
template <typename T, typename F> // partial specialization on first argument
struct conditional<false, T, F> {
typedef F type;
};
这篇关于如何专门针对一系列整数值的C ++模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文