为什么min仍然在constexpr内抱怨?
我有以下代码片段:
#include <iostream>
#include <type_traits>
#include <algorithm>
#include <cstdint>
using T = double;
int main()
{
f();
}
void f() {
T x = 2;
if constexpr(std::is_integral_v<T>)
{
std::cout << std::min(static_cast<int64_t>(2), x);
} else {
std::cout << std::min(1.0, x);
}
}
编译器解释说
<source>:15:57: error: no matching function for call to 'min(int64_t, T&)'
我认为这不会有问题,因为当 T 是双精度时,第一个分支不会被实例化。显然我的理解是错误的。有人可以帮助指出我的理解哪里出了问题吗?
回答
您需要制作f()模板和T模板参数。
template <typename T>
void f() {
T x = 2;
if constexpr(std::is_integral_v<T>)
{
std::cout << std::min(static_cast<int64_t>(2), x);
} else {
std::cout << std::min(1.0, x);
}
}
然后
int main()
{
f<double>();
}
对于constexpr 如果:
(强调我的)
如果 constexpr if 语句出现在模板化实体中,并且条件在实例化后不依赖于值,则在实例化封闭模板时不会实例化丢弃的语句。
在模板之外,完全检查丢弃的语句。
if constexpr不能替代#if预处理指令:void f() { if constexpr(false) { int i = 0; int *p = i; // Error even though in discarded statement } }
- No. My question is why `f()` without the template does not compile? I dont need an answer that works because I know how to make it work too.