常量和非常量 gsl::span 参数的函数模板专用化
Function template specialization for both const and non-const gsl::span argument
假设我有一个函数,它接受任意类型(模板化)的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;
}
如果可能的话,我不想为float
和const 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;
}
相关文章:
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 将重载的成员函数传递给函数模板
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 具有常量引用参数的函数模板专用化
- std::span<const T> 作为函数模板中的参数
- 如何编写一个完美的缩写函数模板?
- 仅在函数模板中为那些定义了函数的类型执行函数
- 如何在C++中伪造虚拟可变参数函数模板?
- 常量和非常量函数作为模板参数参数
- 将常量添加到函数模板指针参数
- 视图和跨步视图以及常量噩梦的函数模板专用化
- 常量字符数组模板与字符常量* 函数重载
- 使用运行时常量实例化的函数模板
- 类型定义模板,接受指向常量和非常量函数的指针
- 常量和非常量 gsl::span 参数的函数模板专用化
- 函数模板如何使用常量限定符推断类型
- 在 c++11 中,当参数类型为常量左值引用与非常量左值引用时,函数模板类型推导的工作原理
- 常量函数指针类型作为模板参数的"invalid use of incomplete type"
- 未能将指向常量数据的指针作为函数模板参数传递