C++ 编译时检查预处理器指令中的类型相等性
C++ compile time checking of type equality in a preprocessor directive
我想在 C++11 的编译时检查两个 POD 类型是否相等。我正在尝试 #define 适合 Float_T 类型的函数名称。这是我尝试过的:
#include <type_traits>
using Float_T = double;
// using Float_T = float;
#if is_same<Float_T, double>::value
#define LOG2 log2
#else
#define LOG2 log2f
#endif
g++ complains: error: extra text after expected end of preprocessing directive
#if is_same<Float_T, double>::value
^
任何人都可以建议一种方法吗?
宏在 source code is being parsed, much before compilation kicks in 时计算,这就是为什么它只不过是一个简单的复制粘贴机制。所以,做这样的事情:
#if is_same<Float_T, double>::value
#define LOG2 log2
#else
#define LOG2 log2f
#endif
实际上是不可能的,因为 is_same
和 #if
在整个编译过程中是在不同的时间计算的。你可以做的是把宏变成一个函数,像这样:
#include <type_traits>
#include <cmath>
using Float_T = double;
template <typename T = Float_T>
typename std::enable_if<std::is_same<T, double>::value, double>::type LOG2(Float_T const& x) {
return log2(x);
}
template <typename T = Float_T>
typename std::enable_if<!std::is_same<T, double>::value, float>::type LOG2(Float_T const& x) {
return log2f(x);
}
// ...
我想在 C++11 的编译时检查两个 POD 类型是否相等。我正在尝试 #define 适合 Float_T 类型的函数名称。这是我尝试过的:
#include <type_traits>
using Float_T = double;
// using Float_T = float;
#if is_same<Float_T, double>::value
#define LOG2 log2
#else
#define LOG2 log2f
#endif
g++ complains: error: extra text after expected end of preprocessing directive
#if is_same<Float_T, double>::value
^
任何人都可以建议一种方法吗?
宏在 source code is being parsed, much before compilation kicks in 时计算,这就是为什么它只不过是一个简单的复制粘贴机制。所以,做这样的事情:
#if is_same<Float_T, double>::value
#define LOG2 log2
#else
#define LOG2 log2f
#endif
实际上是不可能的,因为 is_same
和 #if
在整个编译过程中是在不同的时间计算的。你可以做的是把宏变成一个函数,像这样:
#include <type_traits>
#include <cmath>
using Float_T = double;
template <typename T = Float_T>
typename std::enable_if<std::is_same<T, double>::value, double>::type LOG2(Float_T const& x) {
return log2(x);
}
template <typename T = Float_T>
typename std::enable_if<!std::is_same<T, double>::value, float>::type LOG2(Float_T const& x) {
return log2f(x);
}
// ...