我是C++的初学者。有人能解释一下编译处理函数后的输出吗?非常感谢。
template <typename T>
auto process(T arg)
{
// 4. With constexpr if, to enable the compiler to generate different code based on the type the template is instantiated with:
if constexpr (std::is_same<T, bool>::value)
return !arg;
else if constexpr (std::is_integral<T>::value)
return -arg;
else if constexpr (std::is_floating_point<T>::value)
return std::abs(arg);
else
return arg;
}
int main(){
...
{
auto v1 = process(false); // true
auto v2 = process(42); // -42
auto v3 = process(-42.0); // 42.0
auto v4 = process("42"s); // "42"
}
...
return 0;
}process()的真正代码编译器是在我们在main函数中调用上述代码后生成的。
发布于 2019-06-16 11:53:54
process()的真正代码编译器是在我们在main函数中调用上述代码后生成的。
process()不是一个函数,也不会生成它的编译版本(至少在典型的实现中是这样);相反,您的程序会生成四个单独的函数,即process<bool>、process<int>、process<double>和process<std::string>,每个函数都有自己的编译版本。
这并不是特定于if constexpr的--它只是C++中模板的一般工作方式。
这些编译版本可以完全省略不适用于类型参数的if语句的分支;因此,例如,process<bool>就像是这样定义的:
template<>
bool process<bool>(bool arg)
{
return !arg;
}https://stackoverflow.com/questions/56615898
复制相似问题