"If constexpr"在C ++ 17中无法在非模板函数中工作 [英] "If constexpr" in C++17 does not work in a non-templated function
问题描述
我尝试使用C ++ 17标准.我试图使用C ++ 17 if constexpr
的功能之一.我有一个问题...请看下面的代码.编译没有错误.在下面的代码中,我尝试使用if constexpr
检查它是否是指针.
I tried to play with the C++17 standard. I tried to use one of the features of C++17 if constexpr
. And I had a problem... Please take a look at the following code. This compiles without errors. In the following code, I tried to use if constexpr
to check if it is a pointer.
#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
函数中:
But when I rewrite the above code, as shown below, where if constexpr
is in the main
function:
#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;
问题不在主要功能中.该功能可以是类似于以下功能的任何功能.
Problem is not in the main function. This can be any function similar to the following.
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 the decltype from the input parameter.
推荐答案
我想知道为什么"
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
在 template 内,则不会实例化未采用的分支.它不仅会将不被视为标记的分支视为令牌,而且避免对其进行解析或完全执行语义分析.双方仍将进行分析,并且由于*value
对于int
而言格式不正确,所以这是一个错误.
if constexpr
will not instantiate the branch not taken if it's within a template. It won't just treat the branch not taken as token soup and avoid parsing it or performing semantic analysis entirely. Both sides are still going to be analyzed, and since *value
is ill-formed for int
s, that's an error.
您根本无法使用if constexpr
来避免编译非模板代码.只是避免实例化对于特定专业化可能无效的模板代码.
You simply can't use if constexpr
to avoid compiling non-template code. It's only to avoid instantiating template code that's potentially invalid-for-the-particular-specialization.
这篇关于"If constexpr"在C ++ 17中无法在非模板函数中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!