假设一个模板类:
template <class T>
class Test
{
public:
static bool func(const T &t)
{
// .....
}
};
对于模板参数T, 可以是基础类型:
Test<int>::func(3) Test<double>::func(2.73)
也可以是容器类型:
Test<vector<int>>::func(v1) Test<list<int>>::func(l1) Test<vector<double>>::func(v2)
当它为容器类型时,处理方式和基础类型不同,怎么样实现。想过用半特化,但半特化支持一种特定容器,如
template <class T>
class Test <vector<T>>
{
public:
static bool func(const vector<T> &v)
{
// ....
}
};
以上代码只支持模板参数为vector的特化,想要支持list时,还要重新写一个。有什么办法用尽量简单代码实现。
解决方案
20
是本人的失误,原因是标准容器一般还会有一个Allocator的模板参数,还是要显式地写出来:
template <class T, class TAllocator, template <typename, typename> class TContainer>
class Test<TContainer<T, TAllocator>>
{
public:
static bool func(const TContainer<T, TAllocator>& t);
};