用于替换其参数中的标识符的宏
Macro to replace an identifier in its argument
我需要一个宏,在作为参数传递给它的代码中用另一个标识符替换一个标识符。为了解决我的任务,定义 REPLACE_X_WITH_Y 就足够了,这样这段代码就可以编译:
#define REPLACE_X_WITH_Y(...) __VA_ARGS__ //TODO: replace x with y
int main()
{
REPLACE_X_WITH_Y(
int x = 5;
x = 0;
);
return y;
}
但是,最好有一个通用的宏 REPLACE:
#define REPLACE(x, y, ...) __VA_ARGS__ //TODO: replace x with y
int main()
{
REPLACE(x, y,
int x = 5;
x = 0;
);
return y;
}
C++ 预处理器是否可以使用这些宏?
我的实际用例是在旧编译器上模拟一个特定案例的概念:
#define REQUIRES(...) template<class T_=T, enable_if_t<REPLACE_T_WITH_T_(__VA_ARGS__), int>* = nullptr>
template<typename T> struct S
{
REQUIRES(is_integral_v<T>) int f(T x) {return 0;}
REQUIRES(is_floating_point_v<T>) int f(T x) {return 1;}
};
我看不到执行此类复杂操作的方法,但在您的特定情况下,您不需要它。您需要 SFINAE 的依赖上下文,但它可以很好地按原样启动您的条件,并将其绑定到您可以控制的依赖位:
template <class, bool Value>
struct dependent_bool
: std::integral_constant<bool, Value> { };
#define REQUIRES(...) \
template< \
class Require_T = void, \
::std::enable_if_t< \
dependent_bool<Require_T, (__VA_ARGS__)>::value,\
int \
>* = nullptr \
>
我需要一个宏,在作为参数传递给它的代码中用另一个标识符替换一个标识符。为了解决我的任务,定义 REPLACE_X_WITH_Y 就足够了,这样这段代码就可以编译:
#define REPLACE_X_WITH_Y(...) __VA_ARGS__ //TODO: replace x with y
int main()
{
REPLACE_X_WITH_Y(
int x = 5;
x = 0;
);
return y;
}
但是,最好有一个通用的宏 REPLACE:
#define REPLACE(x, y, ...) __VA_ARGS__ //TODO: replace x with y
int main()
{
REPLACE(x, y,
int x = 5;
x = 0;
);
return y;
}
C++ 预处理器是否可以使用这些宏?
我的实际用例是在旧编译器上模拟一个特定案例的概念:
#define REQUIRES(...) template<class T_=T, enable_if_t<REPLACE_T_WITH_T_(__VA_ARGS__), int>* = nullptr>
template<typename T> struct S
{
REQUIRES(is_integral_v<T>) int f(T x) {return 0;}
REQUIRES(is_floating_point_v<T>) int f(T x) {return 1;}
};
我看不到执行此类复杂操作的方法,但在您的特定情况下,您不需要它。您需要 SFINAE 的依赖上下文,但它可以很好地按原样启动您的条件,并将其绑定到您可以控制的依赖位:
template <class, bool Value>
struct dependent_bool
: std::integral_constant<bool, Value> { };
#define REQUIRES(...) \
template< \
class Require_T = void, \
::std::enable_if_t< \
dependent_bool<Require_T, (__VA_ARGS__)>::value,\
int \
>* = nullptr \
>