相关疑难解决方法(0)

"如果c ++ 17中的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);
}
Run Code Online (Sandbox Code Playgroud)

但是,当我重写上面的代码,如下所示,其中,if constexprmain功能:

#include <iostream>
#include <type_traits>

int main()
{
  auto value = 100;
  if constexpr (std::is_pointer_v<decltype(value)>)
    std::cout << "Ptr to " …
Run Code Online (Sandbox Code Playgroud)

c++ c++17 if-constexpr

19
推荐指数
3
解决办法
1494
查看次数

标签 统计

c++ ×1

c++17 ×1

if-constexpr ×1