gpt4 book ai didi

c++ - 是否可以指定模板类的两个部分? ( '<' 之前和 '< >' 内部的部分)

转载 作者:行者123 更新时间:2023-11-30 01:52:37 25 4
gpt4 key购买 nike

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

在这种情况下,我可以传入任何类似 vector 的容器,只需确保该类具有 operator[]size()

所以问题是:是否可以让 ctor 像数字 3 一样?
或者有什么更好的方法吗?

附言如果有人可以建议更好的标题,那么我会更改它,谢谢!

最佳答案

使用模板模板参数

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;
}

关于c++ - 是否可以指定模板类的两个部分? ( '<' 之前和 '< >' 内部的部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24299894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com