gpt4 book ai didi

c++ - 变量模板和 std::enable_if

转载 作者:搜寻专家 更新时间:2023-10-31 01:35:51 28 4
gpt4 key购买 nike

我可以对模板变量使用 enable_if(或者是否有一些可用的替代技术)。例如

typedef float Float;
typedef double Double;

template<class T>
constexpr Bool IsFloat = std::is_same_v<T, Float>;

template<class T>
constexpr Bool IsDouble = std::is_same_v<T, Double>;

template<class T>
constexpr Bool IsFloatingPoint = IsFloat<T> || IsDouble<T>;

template<class T>
using EnableIfFloatingPoint = std::enable_if_t<IsFloatingPoint<T>>;

template
<
class T,
typename = EnableIfFloatingPoint<T>
>
constexpr T Pi = T(3.1415926535897932384626433832795);

当我尝试使用 Pi<float> 时,Visual Studio 给我一个编译器错误,提示“模板参数太少” ,例如。

最佳答案

马上我建议使用 std::is_floating_point 而不是手动滚动您自己的浮点检测机制。此外,您还可以使用 _v后缀而不是 ::value从 C++17 开始。

正如一些评论中提到的,在变量模板上使用 SFINAE 本身没有多大意义,但您可以实现仅允许浮点类型能够采用 Pi 的值的解决方案。通过尝试将变量模板设置为类型 std::enable_if_t< std::is_floating_point<T>::value, T> ,当然只有在满足条件时才会有推导类型。

template<class T>
using EnableIfFloatingPoint = std::enable_if_t<std::is_floating_point<T>::value, T>;

template<class T>
constexpr T Pi = EnableIfFloatingPoint<T>(3.1415926535897932384626433832795);

Pi<T>对于整数类型 T将无法编译,因为 EnableIfFloatingPoint<T>不会推导出任何类型,但我不会考虑这个 SFINAE。

更好的解决方案是使用 constexpr具有适当 static_assert 的功能模板验证模板已使用“正确”类型实例化的消息。

template<class T>
constexpr T Pi()
{
using is_fp = std::is_floating_point<T>;
static_assert( is_fp::value, "Pi must be instantiated with floating point types.");
return T{3.1415926535897932384626433832795};
}

关于c++ - 变量模板和 std::enable_if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36657585/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com