常量和非常量 gsl::span 参数的函数模板专用化

Function template specialization for both const and non-const gsl::span argument

本文关键字:常量 函数模板 专用 span 非常 gsl 参数      更新时间:2023-10-16

假设我有一个函数,它接受任意类型(模板化)的gsl::span

template <class T>
void foobar(gsl::span<T> x)
{
    cout << "generic" << endl;
}

我想创建一个模板专用化/函数重载,这样当我有一个gsl::span<float>gsl::span<const float>作为参数时,就会使用该函数。

template <>
void foobar(gsl::span<float> x) // or gsl::span<const float>
{
    cout << "specialization" << endl;
}

如果可能的话,我不想为floatconst float编写两个专业,而是使用相同的功能来捕获它们。我有需要两到三个跨度的函数,要编写的专业化数量会呈指数级增长。

我也想拥有同样的双倍专业,所以我怀疑std::is_floating_point<>是否足够精致。我尝试过使用 std::is_same<std::decay_t<T>, float> ,但随后调用变得模棱两可。

这可能吗?

您可以使用重载和 SFINAE...

template <typename T>
std::enable_if_t<!std::is_floating_point<std::decay_t<T>>::value>
foobar(gsl::span<T> x)
{
    std::cout << "generic" << std::endl;
}
template <typename T>
std::enable_if_t<std::is_floating_point<std::decay_t<T>>::value>
foobar(gsl::span<T> x)
{
    std::cout << "floating point specialization" << std::endl;
}