[英]C++ Function Nested Templates
I would like to write a function that can receive both QList and QVector of any type: 我想编写一个可以接收任何类型的QList和QVector的函数:
QList<int> iList;
QVector<int> iVector;
QList<double> dList;
QVector<double> dVector;
all these types must support invocation 所有这些类型都必须支持调用
my_func(iList); my_func(iVector); my_func(dList); my_func(dVector);
My solution 我的解决方案
template <template <typename Elem> typename Cont>
void my_func(const Cont& cont)
{
qDebug() << cont.isEmpty();
Elem el = cont.first();
qDebug() << el;
}
is not compiled: 未编译:
error C2988: unrecognizable template declaration/definition
What is the proper form of such template function? 这种模板功能的正确形式是什么?
There are several errors in your code: 您的代码中有几个错误:
template <template <typename> class Cont, typename Elem>
// ^^^^^ ^^^^^^^^^^^^^
void my_func(const Cont<Elem>& cont)
// ^^^^^^
{
qDebug() << cont.isEmpty();
Elem el = cont.first();
qDebug() << el;
}
The compiler only considers the primary class templates when it tries to locate a match, thus it doesn't know what Elem
is for this line, 编译器在尝试查找匹配时只考虑主类模板,因此它不知道
Elem
对于此行是什么,
Elem el = cont.first();
as Elem
is not what is being specialised. 因为
Elem
不是专业的。
Use either of the following solutions, 使用以下任一解决方案,
template <class Elem, template <class> class Cont>
void my_func(const Cont<Elem>& cont) { ... }
template <class Cont> void my_func(const Cont& cont) {
typename Cont::value_type el = cont.first();
}
You don't need to specify the nested template argument, and you can use auto
to retrieve the element. 您不需要指定嵌套模板参数,也可以使用
auto
来检索元素。
template <typename Cont>
void my_func(const Cont& cont)
{
qDebug() << cont.isEmpty();
auto el = cont.first();
qDebug() << el;
}
Note that you'll need to specify the C++0x or C++11 standard when compiling. 请注意,编译时需要指定C ++ 0x或C ++ 11标准。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.