And*_*own 4 c++ templates metaprogramming c++03
我有一个模板类,接受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();
}
Run Code Online (Sandbox Code Playgroud)
为什么不检查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
) };
};
Run Code Online (Sandbox Code Playgroud)