我尝试使用 C++17 标准。我尝试使用 C++17 if constexpr
的功能之一。我有一个问题......请看下面的代码。这编译没有错误。在下面的代码中,我尝试使用 if constexpr
来检查它是否是一个指针。
#include <iostream>
#include <type_traits>
template <typename T>
void print(T value)
{
if constexpr (std::is_pointer_v<decltype(value)>)
std::cout << "Ptr to " << *value << std::endl; // Ok
else
std::cout << "Ref to " << value << std::endl;
}
int main()
{
auto n = 1000;
print(n);
print(&n);
}
但是当我重写上面的代码时,如下所示,其中if constexpr
在main
函数中:
#include <iostream>
#include <type_traits>
int main()
{
auto value = 100;
if constexpr (std::is_pointer_v<decltype(value)>)
std::cout << "Ptr to " << *value << std::endl; // Error
else
std::cout << "Ref to " << value << std::endl;
}
我得到一个编译错误:
main.cpp:8:32: error: invalid type argument of unary ‘*’ (have ‘int’) std::cout << "Ptr to " << *value << std::endl;
问题不在主函数中。这可以是类似于以下的任何函数。
void print()
{
auto value = 100;
if constexpr (std::is_pointer_v<decltype(value)>)
std::cout << "Ptr to " << *value << std::endl; // Error
else
std::cout << "Ref to " << value << std::endl;
}
int main()
{
print();
}
我想知道为什么 if constexpr
只在模板函数中起作用,即使类型是由输入参数的 decltype 推导出来的。
最佳答案
I would like to know why "
if constexpr
" works only in template functions, even if the type is deduced by thedecltype
from the input parameter.
这是设计使然。
if constexpr
不会实例化未采用的分支,如果它在模板 中。它不会只是将未被视为 token 汤的分支处理并避免对其进行解析或完全执行语义分析。双方仍将被分析,由于 *value
对于 int
而言格式错误,这是一个错误。
您根本无法使用 if constexpr
来避免编译非模板代码。这只是为了避免实例化可能对特定特化无效的模板代码。
关于c++ - C++17 中的 "If constexpr"在非模板函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53044651/