Problem compiling template function with typename for dependent names

A

antoniogarcar

Hi all,

I have a short question. The following program does not compile using g++4.6.3, ¿why?


#include <list>

template <class T>
void empty (typename std::list<T>::iterator it)
{}

int main()
{
std::list<int> l;
empty(l.begin());
}
 
S

SG

Am 20.11.2012 09:33, schrieb (e-mail address removed):
The following program does not compile using g++4.6.3, ¿why?

#include <list>

template <class T>
void empty (typename std::list<T>::iterator it)

- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This is a non-deducible context. Or, as Stephan T. Lavavej would say
"The double colon between T and 'iterator' prevents the compiler from
deducing T" (or something like that).
{}

int main()
{
std::list<int> l;
empty(l.begin());
}

Here, the compiler won't deduce the template parameter T as a general
rule. You can't expect the compiler to try every possible T and see what
fits. There are other cases where there is no "solution" for T:

template<class T>
struct foo {
typedef int blah;
}

template<class T>
void empty(typename foo<T>::blah);

int main()
{
empty(42); // What's T ?!
}

HTH,
SG
 
Z

Zhihao Yuan

template <class T>
void empty (typename std::list<T>::iterator it)
{}

First, like SG said, a typename is not deducible. Second, operations
work on a iterator should be generalized regarding to the *type* of
the iterator, not the type of the value. Try this:

template <typename It>
void empty (It it, typename std::enable_if<
std::is_convertible<
typename std::iterator_traits<It>::iterator_category,
std::bidirectional_iterator_tag>::value>::type* = 0) {
// or forward_iterator_tag, etc.
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top