怎么样特化类型为容器的模板参数

C++语言 码拜 8年前 (2016-04-26) 902次浏览
假设一个模板类:

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

引用:

贴上完整代码:

#include <vector>
#include <list>
#include <iostream>
using namespace std;
template <class T>
class Test
{
public:
	static bool func(const T &t)
	{
		cout << t << endl;
		return true;
	}
};
template <class T, template <typename> class TContainer>
class Test<TContainer<T>>
{
public:
	static bool func(const TContainer<T> &t)
	{
		TContainer<T>::const_iterator iter;
		for (iter = t.begin(); iter != t.end(); ++i)
		{
			cout << *iter << " "
		}
		cout << endl;
		return true;
	}
};
int main()
{
	int a = 100;
	Test<int>::func(a);
	int array[5] = {1, 2, 3, 4, 5};
	vector<int> v(array, array + 5);
	Test<vector<int>>::func(v);
	return 0;
}

还是编译不通过啊。

是本人的失误,原因是标准容器一般还会有一个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);
};

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明怎么样特化类型为容器的模板参数
喜欢 (0)
[1034331897@qq.com]
分享 (0)