c++ - C++17 中的 "If constexpr"在非模板函数中不起作用

标签 c++ c++17 if-constexpr

我尝试使用 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 constexprmain函数中:

#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 the decltype from the input parameter.

这是设计使然。

if constexpr 不会实例化未采用的分支,如果它在模板 中。它不会只是将未被视为 token 汤的分支处理并避免对其进行解析或完全执行语义分析。双方仍将被分析,由于 *value 对于 int 而言格式错误,这是一个错误。

您根本无法使用 if constexpr 来避免编译非模板代码。这只是为了避免实例化可能对特定特化无效的模板代码。

关于c++ - C++17 中的 "If constexpr"在非模板函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53044651/

相关文章:

c++ - if constexpr 在递归通用 lambda : different compiler behavior

c++ - 在 C++11 中使用 CRTP 作为抽象静态方法的替代方法

c++ - 为什么我的二进制文件的大小取决于数组的大小?

c++ - 实例化函数模板时省略模板类型参数是否合法?

c++ - 使用引用的 constexpr 静态成员作为模板参数

c++ - 在通用 lambda 中使用 `if constexpr` 访问成员类型需要两个分支的格式都正确 - gcc 与 clang

c++ - 我的功能代码出错(停止工作)

C++ 多态性 - 自动检测派生类型

c++ - 以在使用临时对象调用时生成编译器错误的方式重载方法

c++ - 根据编译器优化和代码性能,`if constexpr` 与 `if`