【发布时间】:2020-11-12 17:10:33
【问题描述】:
我正在尝试使用 C++17 if constexpr 进行条件编译,但它的行为并不符合我的预期。
比如下面的代码,C++仍然编译宏X2定义的代码,
#include <map>
#include <string>
#include <iostream>
#include <type_traits>
#define X1 pp("x")
#define X2 pp("x", "x")
void pp(const std::string str)
{
std::cout << str << std::endl;
}
int main()
{
std::map<std::string, int> map;
if constexpr (std::is_null_pointer_v<decltype(map)>)
X2;
else
X1;
}
并吐出以下错误消息:
1.c:6:23: error: too many arguments to function ‘void pp(std::__cxx11::string)’
#define X2 pp("x", "x")
^
1.c:18:3: note: in expansion of macro ‘X2’
X2;
^~
如何跳过 X2 的编译?
【问题讨论】:
-
if constexpr是std::enable_if的替代品,而不是#if。 -
我最近做了一个quiz on this issue 和我note in my answer,它并不是要表现得像例如解除
static_asserts等
标签: c++ if-statement templates c++17 constexpr