class trytemplate
{
public:
//////// 1
template <typename T>
trytemplate(const T& p)
{
std::cout << p << std::endl;
}
//////// 2
template <typename U>
trytemplate(const std::vector<U>& p)
{
std::cout << p[0] << " " << p.size() << std::endl;
}
//////// 3
template <typename U, typename V>
trytemplate(const V<U>& p)
{
std::cout << p[0] << " " << p.size() << std::endl;
}
};
ctor 2工作正常,但我想使其类似于3(3不编译)。
这样我可以做类似的事情:
int i = 123;
trytemplate o1(i); // call ctor 1
std::vector<float> v1(1, 123.0f);
trytemplate o2(v1); // ideally can be deduced by compiler, and call ctor 3
MyVector<float> v2(1, 123.0f);
trytemplate o3(v2); // ideally can be deduced by compiler, and call ctor 3
在这种情况下,我可以传入任何类似于矢量的容器,只需确保该类具有operator[]
and即可size()
。
所以问题是:是否可以使ctor像数字3?
还是有更好的方法?
PS:如果有人可以建议一个更好的标题,那么我会更改它,谢谢!
使用模板template参数
template <template<typename> class V, typename U>
trytemplate(const V<U>& p)
{
std::cout << p[0] << " " << p.size() << std::endl;
}
您还可以添加可变参数模板以接受采用多个模板参数的类模板。
template <template<typename...> class V, typename... Params>
trytemplate(const V<Params...>& p)
{
std::cout << p[0] << " " << p.size() << std::endl;
}
请注意,如果您使用的是非可变(第一个)版本,则您传入的类模板应仅使用单个模板参数。这意味着它不能与之一起使用,std::vector
因为它需要第二个模板参数,即分配器类型(其默认参数为std::allocator<T>
)。如果您的编译器不支持可变参数模板(例如不具有Nov CTP的VS2012),请使用此模板
template <template<typename, typename> class V, typename U, typename A>
trytemplate(const V<U, A>& p)
{
std::cout << p[0] << " " << p.size() << std::endl;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句