Question

I would like to write a function that can receive both QList and QVector of any type:

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?

Was it helpful?

Solution

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;
}

OTHER TIPS

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 el = cont.first();

as Elem is not what is being specialised.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top