C++ 1z将引入"constexpr if" - 如果将根据条件删除其中一个分支.似乎合理有用.
但是,没有constexpr关键字是不可能的?我认为在编译期间,编译器应该知道编译时间是否已知.如果是,即使是最基本的优化级别也应该删除不必要的分支.
例如(参见godbolt:https://godbolt.org/g/IpY5y5 ):
int test() {
const bool condition = true;
if (condition) {
return 0;
} else {
// optimized out even without "constexpr if"
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
Godbolt探险家表示,即使是带有-O0的gcc-4.4.7也没有编译"返回1",所以它实现了constexpr所承诺的.显然,当条件是constexpr函数的结果时,这样的旧编译器将无法这样做,但事实仍然存在:现代编译器知道条件是否为constexpr,并且不需要我明确地告诉它.
所以问题是:
为什么"constexpr if"需要"constexpr"?
if constexpr()和之间有什么区别if()?
我何时何地可以同时使用它们?
我有一个简单的递归函数来打印参数包中的每个参数
#include <iostream>
template<typename T, typename... Args>
void printArgs(T first, Args... rest) {
std::cout << first << " ";
if constexpr (sizeof...(rest) > 0) { // doesn't compile without constexpr
printArgs(rest...);
} else {
return;
}
}
int main() {
printArgs(1, 2, "hello");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Q1:为什么程序需要constexpr编译?Q2:条件不应该是吗?因为如果大小是,我再次调用,那么不会是空的?(空着可以吗?)if
sizeof...(rest) > 11printArgsrest
我看到了类似的问题,例如“constexpr if”与“if”的优化 - 为什么需要“constexpr”?,但我不明白这些答案与我的案例有什么关系。