如何为模板化类型提供模板函数的专门化
How do I provide specialization of template function for a templated type?
我有一个模板函数,我想为它提供专门化,以便处理boost::optional<T>
。然而,如果我想让我的专业化处理所有类型的boost::optional<T>
,而不是像boost::optional<int>
这样的特定类型,我似乎无法为这种场景找到合适的语法。
这里有一个可编译的例子:
#include <boost/optional.hpp>
template <typename T>
void foo(const T& t)
{}
// This works.
template<>
void foo<int>(const int& t)
{}
// This works.
template<>
void foo<boost::optional<int>>(const boost::optional<int>& t)
{}
// What to do in this case??
// template <typename U>
// void foo<boost::optional<U>>(const boost::optional<U>& t)
// {}
int main() {}
不要专门化。请改为提供过载。
template <typename U>
void foo(const boost::optional<U>& t)
{
}
不能部分专用化模板函数。但你可以为class
做这件事
namespace detail
{
template <typename T>
struct foo_impl
{
void operator () (const T&) const {};
}
template <>
struct foo_impl<int> // Full specialization for int
{
void operator () (int) const {};
}
template <>
struct foo_impl<boost::optional<int>> // Full specialization for boost::optional<int>
{
void operator () (const boost::optional<int>&) const {};
}
template <typename T>
struct foo_impl<boost::optional<T>> // Partial specialization for boost::optional<T>
{
void operator () (const boost::optional<T>&) const {};
}
}
template <typename T>
void foo(const T& t)
{
detail::foo_impl<T>{}(t); // Forward to correct struct
}
否则你可以提供过载(可能更简单)
template <typename T>
void foo(const T&) {}
void foo(int) {}
void foo(const boost::optional<int>&) {}
template <typename T>
void foo(const boost::optional<T>&) {}
关于过载方法的注意事项:
- `foo(42)` and `foo<int>(42)` won't call the same function
- and similarly, with `boost::optional<int> opt_i;`,
`foo(opt_i)`, `foo<int>(opt_i)` and `foo<boost::optional<int>>(opt_i)`
will call 3 different functions.
相关文章:
- 尝试根据类中 typedef 的存在来专门化模板函数
- 如何基于模板化类的基类专门化成员函数
- 专门化模板覆盖函数/避免对象切片
- 如何使用模板化类专门化模板化函数?
- 线程 std::调用未知类型,无法专门化函数错误
- 如何在编译时专门化大型模板函数中的小部分
- 模板函数,其中一个参数需要专门化,而另一个不需要
- 错误 C2893 无法专门化函数模板'unknown-type std::invoke(_Callable &&,_Types &&...)'
- 从 std 命名空间中专门化函数模板的想法有多糟糕?
- 为模板函数专门化一个模板类
- 基于参数值的c++模板成员函数专门化
- 如何确定函数专门化的主模板
- 等价参数的c++函数专门化
- 基于运行时值调用不同的模板函数专门化
- 跨库的模板函数专门化符号匹配
- 模板函数专门化,c++
- 如何使用type_traits或模板函数专门化来整合模板方法
- 如何在子类中重载模板化函数(专门化)
- 可变模板函数:专门化头/尾和空基准情况
- 不允许void的部分函数专门化-替代解决方案