2014-04-29 148 views
0

我想编写一个可以接收任何类型的两个的QList和QVector功能:C++函数嵌套模板

QList<int> iList; 
QVector<int> iVector; 
QList<double> dList; 
QVector<double> dVector; 

所有这些类型都必须支持调用

my_func(iList); my_func(iVector); my_func(dList); my_func(dVector); 

我的解决方案

template <template <typename Elem> typename Cont> 
void my_func(const Cont& cont) 
{ 
    qDebug() << cont.isEmpty(); 
    Elem el = cont.first(); 
    qDebug() << el; 
} 

未编译:

error C2988: unrecognizable template declaration/definition 

这种模板函数的正确形式是什么?

回答

1

有在你的代码的几个误区:

template <template <typename> class Cont, typename Elem> 
//       ^^^^^  ^^^^^^^^^^^^^ 
void my_func(const Cont<Elem>& cont) 
//      ^^^^^^ 
{ 
    qDebug() << cont.isEmpty(); 
    Elem el = cont.first(); 
    qDebug() << el; 
} 
1

编译器只考虑当它试图找到一个匹配的初级类模板,因此不知道什么Elem是这条线,

Elem el = cont.first(); 

as Elem是不是什么专业。

使用以下两种解决方案,

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(); 
} 
+0

'Cont :: value_type'应该是'typename Cont :: value_type'。 – Constructor

+0

这里是一个错字:'my_func(const Cont&cont); {'。 – Constructor

+0

@Constructor谢谢!固定。 – mockinterface

0

你并不需要指定嵌套模板参数,你可以使用auto检索元素。

template <typename Cont> 
void my_func(const Cont& cont) 
{ 
    qDebug() << cont.isEmpty(); 
    auto el = cont.first(); 
    qDebug() << el; 
} 

请注意,您需要在编译时指定C++ 0x或C++ 11标准。