参考这个问题.用于初始化constexpr变量的核心常量表达式是错误的y.这么多是给定的.
但如果我试着if变成if constexpr:
template <typename T>
void foo() {
constexpr int x = -1;
if constexpr (x >= 0){
constexpr int y = 1 << x;
}
}
int main(){
foo<int>();
}
Run Code Online (Sandbox Code Playgroud)
错误仍然存在.GCC 7.2仍然给出:
error: right operand of shift expression '(1 << -1)' is negative [-fpermissive]
Run Code Online (Sandbox Code Playgroud)
但我认为语义检查应该在废弃的分支上保持不成形.
constexpr但是,通过lambda 进行间接确实有帮助:
template <typename T>
void foo(){
constexpr int x = -1;
constexpr auto p = []() constexpr { return x; }; …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 C++17if 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;
}
Run Code Online (Sandbox Code Playgroud)
并吐出此错误消息:
#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; …Run Code Online (Sandbox Code Playgroud)