【发布时间】:2016-08-22 11:23:51
【问题描述】:
如何编写一个接受嵌套模板的模板函数?
例如,我想编写以下函数:
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);
【问题讨论】:
-
是的,那个看起来很像复制品。我建议只使用一个模板参数,而不是费尽心机。