gpt4 book ai didi

c++ - 嵌套模板(模板模板参数)

转载 作者:太空狗 更新时间:2023-10-29 23:43:54 24 4
gpt4 key购买 nike

如何编写接受嵌套模板的模板函数?

例如,我想编写以下函数:

void print(const T1<T2<T3>> &container);

尝试过:

template<
template<typename> class T1,
template<typename> class T2,
class T3
>
void print(const T1<T2<T3>> &container) {
for (auto &e : container)
for (auto x : e)
std::cout<<e<<' ';
std::cout<<'\n';
}

int main()
{
std::vector<std::deque<int>> c = {{1,2},{3}};
print(c);
return 0;
}

g++编译错误:

a.cc: In function ‘int main()’:
a.cc:23:14: error: no matching function for call to ‘print(std::vector<std::deque<int> >&)’
print(c);
^
a.cc:12:10: note: candidate: template<template<class> class T1, template<class> class T2, class T3> void print(const T1<T2<T3> >&)
void print(const T1<T2<T3>> &container) {
^
a.cc:12:10: note: template argument deduction/substitution failed:
a.cc:23:14: error: wrong number of template arguments (2, should be 1)
print(c);
^
a.cc:8:32: note: provided for ‘template<class> class T1’
template<typename> class T1,
^

来自 Clang 的编译错误:

a.cc:23:7: error: no matching function for call to 'print'
print(c);
^~~~~
a.cc:12:10: note: candidate template ignored: substitution failure : template template argument has different template parameters than its corresponding
template template parameter
void print(const T1<T2<T3>> &container) {
^

还试过:

template<
template<template<typename> class> class T1,
template<typename> class T2,
class T3
>
void print(const T1<T2<T3>> &container);

但是在推导之前还是有编译错误:

a.cc:12:25: error: template argument for template template parameter must be a class template or type alias template
void print(const T1<T2<T3>> &container) {
^

---- 编辑----

如果我想返回一个指向其中一个类型的指针怎么办?

 T3 get(const T1<T2<T3>> &container);

最佳答案

不过,我更喜欢您使用单个模板并从中选择 typedef。

类似于:

template<typename T1>
void print(const T1& container) { //As opposed to const T1<T2<T3>> &container
using T2 = typename T1::value_type;
using T3 = typename T2::value_type;

for (auto &e : container)
for (auto x : e)
std::cout<<x<<' ';
std::cout<<'\n';
}

但如果您必须按自己的方式行事,那么这将有效(std::vectorstd::deque 实际上是用两个模板参数声明的,尽管分配器是默认的):

template<
template<typename, typename> class T1,
template<typename, typename> class T2,
typename AllocT1, typename AllocT2,
typename T3
>
void print(const T1<T2<T3, AllocT2>, AllocT1> &container) {
for (auto &e : container)
for (auto x : e)
std::cout<<x<<' ';
std::cout<<'\n';
}

但是有一个更简洁的解决方案:

template<typename T1, 
typename T2 = typename T1::value_type,
typename T3 = typename T2::value_type>
T3 print(const T1& container){

for (auto &e : container)
for (auto x : e)
std::cout<<x<<' ';
std::cout<<'\n';

return T3();
}

选择权完全属于您。 :-)

编辑:

What if I'd like to return a pointer to one of it's type?

T3 get(const T1<T2<T3>> &container);

在 C++14 中,您可以简单地使用 auto 占位符返回类型,或者使用上面的后一种解决方案。

关于c++ - 嵌套模板(模板模板参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39078287/

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