gpt4 book ai didi

c++ - 嵌套模板函数采用 2 个具有相同内部类型的容器

转载 作者:搜寻专家 更新时间:2023-10-31 00:07:40 24 4
gpt4 key购买 nike

我正在尝试编写的函数大致类似于采用两个容器实例的函数(假设现在它们是相同的),包含相同的类型并将它们合并。所以这是我的 vector 函数:

template<typename T>
void test(std::vector<T> v1, std::vector<T> v2) {
std::cout << "called nested for c\n";
}

而且有效。

现在我想要一个适用于集合或 vector 的方法。我试试这个:

template<typename T, template <typename> typename C >
void test(C<T> v1, C<T> v2) {
std::cout << "called nested for c<t>\n";
}

得到

nestedt.cc:33:6: note: template argument deduction/substitution failed: nestedt.cc:43:12: error: wrong number of template arguments (3, should be 1) test(s, s); ^ nestedt.cc:32:51: note: provided for ‘template class C’ template typename C > ^

我试试

template< template <typename T> typename C >
void test(C<T> v1, C<T> v2) {}

std::set<int> s = {1,2};
test(s, s);

那是行不通的:

nestedt.cc:32:6: note: template argument deduction/substitution failed: nestedt.cc:42:12: note: cannot convert ‘s’ (type ‘std::set’) to type ‘int’ test(s, s); ^

所以我试试

template<typename C, typename T >
void test(C<T> v1, C<T> v2) {}

得到

nestedt.cc:32:6: note: candidate: template void test(C, C) void test(C v1, C v2) { ^ nestedt.cc:32:6: note: template argument deduction/substitution failed: nestedt.cc:42:12: note: couldn't deduce template parameter ‘T’ test(s, s); ^

我觉得我什至还没有完全理解模板在 C++ 中的实际工作方式,这真是令人难过。同样在现实中,我希望容器不同。理想情况下能够以某种方式指定一组有限的允许容器。而且它们并不是真正的 std::容器。

请注意,最终目标是能够使用 2 个不同的容器,所以类似于 test(vector<int>, set<int>) .修改容器是不可能的。

最佳答案

我相信你要找的是

template<template <typename...> typename Cont1, 
template <typename...> typename Cont2,
typename... T>
void test(Cont1<T...> a, Cont2<T...> b) { }

在上面template <typename...> typename Cont1声明一个模板模板类型和template <typename...> typename Cont2声明另一个,这样你就可以拥有两种不同的容器类型。双方分享T...所以每个模板容器都需要有一个匹配的模板参数列表。这意味着

test(std::map<int, int>{}, std::map<int, int>{});
test(std::set<int>{}, std::set<int>{});
test(std::vector<int>{}, std::set<int>{});

一切正常,但

test(std::map<int, int>{}, std::vector<int>{});
test(std::map<int, int>{}, std::set<int>{});

不会。

关于c++ - 嵌套模板函数采用 2 个具有相同内部类型的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52526393/

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