我有一个模板类,可以接受1到8个整数参数。每个参数的允许范围是0..15。每个参数的默认值16允许我检测未使用的参数。
我希望用户提供的参数数量可用作编译时常量。我可以使用模板助手类和许多部分专业化来完成这项工作。
我的问题是,我可以使用一些递归元编程来清理它。我有什么作品,但感觉它可以在语法上得到改善。
遗憾的是,我无法使用变量模板和其他任何c ++ 0x。
#include <stdint.h>
#include <iostream>
template<uint8_t p0,uint8_t p1,uint8_t p2,uint8_t p3,uint8_t p4,uint8_t p5,uint8_t p6,uint8_t p7>
struct Counter { enum { COUNT=8 }; };
template<uint8_t p0,uint8_t p1,uint8_t p2,uint8_t p3,uint8_t p4,uint8_t p5,uint8_t p6>
struct Counter<p0,p1,p2,p3,p4,p5,p6,16> { enum { COUNT=7 }; };
template<uint8_t p0,uint8_t p1,uint8_t p2,uint8_t p3,uint8_t p4,uint8_t p5>
struct Counter<p0,p1,p2,p3,p4,p5,16,16> { enum { COUNT=6 }; };
template<uint8_t p0,uint8_t p1,uint8_t p2,uint8_t p3,uint8_t p4>
struct Counter<p0,p1,p2,p3,p4,16,16,16> { enum { COUNT=5 }; };
template<uint8_t p0,uint8_t p1,uint8_t p2,uint8_t p3>
struct Counter<p0,p1,p2,p3,16,16,16,16> { enum { COUNT=4 }; };
template<uint8_t p0,uint8_t p1,uint8_t p2>
struct Counter<p0,p1,p2,16,16,16,16,16> { enum { COUNT=3 }; };
template<uint8_t p0,uint8_t p1>
struct Counter<p0,p1,16,16,16,16,16,16> { enum { COUNT=2 }; };
template<uint8_t p0>
struct Counter<p0,16,16,16,16,16,16,16> { enum { COUNT=1 }; };
template<uint8_t p0,uint8_t p1=16,uint8_t p2=16,uint8_t p3=16,
uint8_t p4=16,uint8_t p5=16,uint8_t p6=16,uint8_t p7=16>
struct MyClass {
void printArgCount() {
std::cout << Counter<p0,p1,p2,p3,p4,p5,p6,p7>::COUNT << std::endl;
}
};
main() {
MyClass<4,7,8,12,15,1> foo;
foo.printArgCount();
}
答案 0 :(得分:5)
为什么不检查出现的第一个16
?
template <uint8_t p0, ...>
struct Counter {
enum { COUNT = (p1 == 16 ? 1 :
p2 == 16 ? 2 :
p3 == 16 ? 3 :
p4 == 16 ? 4 :
p5 == 16 ? 5 :
p6 == 16 ? 6 :
p7 == 16 ? 7 :
8
) };
};
答案 1 :(得分:2)
你可以做到这一点,但它仍然没有其他人使用c ++ 11提供的其他解决方案那么漂亮/漂亮:
template< uint8_t p0 = 16,uint8_t p1 = 16,uint8_t p2 = 16,uint8_t p3 = 16,uint8_t p4 = 16,uint8_t p5 = 16,uint8_t p6 = 16,uint8_t p7 = 16>
struct Counter
{
enum { COUNT= int(p0!=16) + int(p1!=16) + int(p2!=16) + int(p3!=16) + int(p4!=16) + int(p5!=16) + int(p6!=16) + int(p7!=16) };
int count() const
{ return COUNT; }
};
答案 2 :(得分:0)
您可以递归设置计数器,如下所示:
template<typename>
struct Counter;
template<>
struct Counter<> { static const int COUNT = 0;};
template<typename T, typename... Args>
struct count<T, Args...> //partial specialization
{ static const int value = 1 + count<Args...>::COUNT;};