C ++预处理器条件参数 [英] C++ preprocessor conditional parameter
问题描述
请注意C ++ 03!任何C ++ 11解决方案都不适合我,但只是为了知识而发布它们。
Please note C++03! any C++11 solutions are not good for me, but do post them just for knowledge sake.
我知道预处理器可以做以下事情:
I know the preprocessor can do things like:
#define FOO 4
#if FOO == 4
cout<<"hi"<<endl;
#endif
我需要的是:
#define BAR(X)\
#if X == 4\
cout<<"hi"<<endl;\
#endif
main.cpp
BAR(4)
我不喜欢看看为什么在预处理器时间内无法获得所有需要的信息。
I don't see why all the needed information wouldn't be available in preprocessor time.
所以,请告诉我如何实现这种行为。
So, Please tell me how to achieve this kind of behavior.
编辑1:
正常if条件对我的情况不起作用,因为我也做了类似的事情:
edit 1: A normal if condition won't work for my case, because I also do things like:
#define BAR(X)\
#if X == 4\
int poop;
#elif
double poop;
#endif
推荐答案
这里的一些答案更好相对于其它的。
我接受的那个是由Christian Kiewiet在评论中发布的,但这对我来说是最准确的。
以下是扩展版本:
Some answers here were better than others. The one I accepted was posted by Christian Kiewiet in a comment, but it was the most accurate for my purpose. Here is the expanded version:
useCases.h
useCases.h
enum UseCases{
useCase1=0,
useCase2,
useCaseNumber//always last for iterations
}
specializer.h
specializer.h
#include "useCases.h"
<template UseCases theCase>
struct StaticCase{
//empty, thus accidents calling from this can't happen
}
//specialization
template<>
class StaticCase<UseCases::useCase1>{
typedef int T;
static foo(T arg){cout<<"case1";};
}
template<>
class StaticCase<UseCases::useCase2>{
typedef double T;
static foo(){cout<<"case2";};
}
现在,我可以做到
#define BAR1(useCase) StaticCase<useCase>::foo();
或
#define BAR2(useCase) StaticCase<useCase>::T var;
和电话:
BAR1(UseCases::useCase1)//output - case1
BAR1(UseCases::useCase2)//output - case2
这篇关于C ++预处理器条件参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!