@
bluearc @
abc612008 不对,模板可以解决,需要手动把所有可能的取值写出来,例如:
test<0x1f0, 0x1f1, 0x1f2>(i);
如果能接受非标准扩展的话,有种办法可以把取值加到宏列表里:
#include <cstdio>
#include <cstdlib>
template<int N>
void func();
template<typename T = void>
void test(int n)
{
puts("test() failed!");
}
template<int N, int... ints>
void test(int n)
{
printf("test<%i>(%i)\n", N, n);
if (n == N) {
func<N>();
} else {
test<ints...>(n);
}
}
#define PUSHVAL _Pragma("push_macro(\"VALUES\")")
#define POPVAL _Pragma("pop_macro(\"VALUES\")")
#define VALUES 2
template<>
void func<2>()
{
puts("func<2>()");
}
PUSHVAL
#undef VALUES
#define VALUES POPVAL VALUES, 3
template<>
void func<3>()
{
puts("func<3>()");
}
PUSHVAL
#undef VALUES
#define VALUES POPVAL VALUES, 5
template<>
void func<5>()
{
puts("func<5>()");
}
PUSHVAL
#undef VALUES
#define VALUES POPVAL VALUES, 7
template<>
void func<7>()
{
puts("func<7>()");
}
int main(int argc, char** argv)
{
if (argc != 2) {
printf("usage: %s <int>\n", argv[0]);
return 1;
}
int n = (int)strtoul(argv[1], nullptr, 0);
printf("n = %i\n", n);
test<VALUES>(n);
}
上述方法在 gcc 中有效,msvc 无效。