Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Problem compiling template function with typename for dependent names (http://www.velocityreviews.com/forums/t954658-problem-compiling-template-function-with-typename-for-dependent-names.html)

antoniogarcar@gmail.com 11-20-2012 08:33 AM

Problem compiling template function with typename for dependent names
 
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());
}

SG 11-20-2012 09:57 AM

Re: Problem compiling template function with typename for dependentnames
 
Am 20.11.2012 09:33, schrieb antoniogarcar@gmail.com:
>
> 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


Antonio Garrido 11-20-2012 10:53 AM

Re: Problem compiling template function with typename for dependent names
 

> HTH,
>
> SG


Thank you. That helps.

Zhihao Yuan 11-20-2012 10:59 AM

Re: Problem compiling template function with typename for dependent names
 
On Tuesday, November 20, 2012 2:33:41 AM UTC-6, Antonio Garrido wrote:
> 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.
}


All times are GMT. The time now is 09:34 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.