繁体   English   中英

如果 constexpr,你可以替换 enable_if 来禁用它的功能吗?

[英]can you replace enable_if to disable a function it if constexpr?

所以我知道你可以使用 enable_if 来禁用函数模板(例如,如果类型不是整数) - 但是你可以用 constexpr 做同样的事情吗?

即是否有这样的等价物:

template<class T, typename = std::enable_if_t<std::is_integral_v<T>> >
T test2()
{
    return {};
}

使用 constexpr - 类似于:

template <typename T>
T test()
{
    // we expect various integral and floating point types here
    if constexpr (std::is_integral_v<T>)
    {
        T output{};
        return output;
    }
    else
    {
       // trigger compiler error
       return{};
    }
}

所以我想要:

test(1); // compile ok
test(std::string("hello")); // compile fail

您可以将static_assert与类型相关的表达式一起使用,该表达式在constexpr if 中始终为false

template<class> inline constexpr bool dependent_false_v = false;
template <> inline constexpr bool dependent_false_v<decltype([](){})> = true; // requires C++20
template <typename T>
T test(T)
{
    // we expect various integral and floating point types here
    if constexpr (std::is_integral_v<T> || std::is_floating_point_v<T>)
    {
        T output{};
        return output;
    }
    else
    {
       // trigger compiler error
       static_assert(dependent_false_v<T>);
    }
}

就这么简单:

template <typename T>
T test()
{
  static_assert(std::is_integral_v<T>);
  T output{};
  return output;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM