C++ Insights ( https://cppinsights.io/ ) 能够做到这一点(并且更普遍地扩展“高级”语法糖 C++ 结构。它基于 Clang,因此它对代码的理解为尽可能好,并支持最新标准。
例如它将扩展
extern "C" void printf(...);
template<typename T>
int foo(T t)
{
if constexpr(sizeof(T) == 4) {
printf("int: %d", t);
}
else {
printf("something else: %d", (int)t);
}
}
int main()
{
const char arr[10]{2,4,6,8};
for(const char& c : arr)
{
foo(c);
}
}
进入
extern "C" void printf(...);
template<typename T>
int foo(T t)
{
if constexpr(sizeof(T) == 4) {
printf("int: %d", t);
}
else {
printf("something else: %d", (int)t);
}
}
/* First instantiated from: insights.cpp:19 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
int foo<char>(char t)
{
if constexpr(false) {
} else /* constexpr */ {
printf("something else: %d", static_cast<int>(t));
}
}
#endif
int main()
{
const char arr[10] = {2, 4, 6, 8, '\0', '\0', '\0', '\0', '\0', '\0'};
{
char const (&__range1)[10] = arr;
const char * __begin1 = __range1;
const char * __end1 = __range1 + 10L;
for(; __begin1 != __end1; ++__begin1) {
const char & c = *__begin1;
foo(c);
}
}
return 0;
}