Fra*_*ank 5 c++ templates template-specialization
我使用以下代码编译时遇到问题:
template <typename T,
template <class T, class Allocator = std::allocator<T> > class C>
bool is_in(const C<T>& a, const C<T>& b);
template <typename T, std::vector> // HERE
bool is_in(const std::vector<T>& a, const std::vector<T>& b)
{
return false; // implementation tbd
}
...
vector<int> a, b;
cout << is_in(a,b) << endl;
Run Code Online (Sandbox Code Playgroud)
错误消息是(在标有"HERE"的行上):
error: 'std::vector' is not a type
Run Code Online (Sandbox Code Playgroud)
(当然,我已经从std中包含了矢量!).有什么建议吗?我摆弄了一段时间,但我已经到了可以使用一些帮助的地步:-)我需要部分专门化初始模板声明,以便我可以根据实际的类型设置编译器开关实现容器C(将有一个is_in用于集合,一个用于向量,一个用于范围......,每次使用不同的算法).
谢谢!
标准不允许功能模板的部分特化.
一个简单的解决方案是:使用过载.
template <typename T>
bool is_in(const std::vector<T>& a, const std::vector<T>& b)
{
return false; // implementation tbd
}
Run Code Online (Sandbox Code Playgroud)
这是重载的功能模板.它不是部分专业化.
或者,你可以这样做:
namespace detail
{
template<typename T, typename C>
struct S
{
static bool impl(const C & a, const C & b)
{
//primary template
//...
}
}
template<typename T>
struct S<T, std::vector<T> >
{
static bool impl(const std::vector<T> & a, const std::vector<T> & b)
{
//partial specialization for std::vector
return false;
}
}
}
template <typename T, template <class T, class Allocator = std::allocator<T> > class C>
bool is_in(const C<T>& a, const C<T>& b)
{
return detail::S<T, C<T> >::impl(a,b);
}
Run Code Online (Sandbox Code Playgroud)