Strange error of expected GCC primary expression ... '

Possible duplicate:
Templates: the template function does not work well with the & rsquo; class s member function

template <typename T>
struct A
{
    template <int I>
    void f();
};

template <typename T>
void F(A<T> &a)
{
    a.f<0>(); // expected primary-expression before ‘)’ token
}

int main()
{
    A<int> a;

    a.f<0>(); // This one is ok.
}

What does it mean?

+5
source share
3 answers

When a dependent name is used to refer to a nested template, the nested name must be added with a keyword templateto help the compiler understand that you are referencing the nested template and correctly parsing the code.

template <typename T>
void F(A<T> &a)
{
    a.template f<0>();
}

Inside, the mainname ais independent, so you do not need an additional keyword template. Inside the Fname adepends, so a keyword is needed.

typename . .

+16

, ...

a.f < 0 ...gibberish....

Andrey .

+1

, , , , , , .

#include <iostream>

struct A { 
  template<typename T> 
  static A f(T) { 
    return A(); 
  } 

  template<typename T> operator T() { return T(); }
}; 

template<typename U> 
int g() { 
  U u;
  typedef A (*funcPtrType)(int());
  return !(funcPtrType)u.f < int() > (0); 
}

int main() {
  std::cout << g<A>() << std::endl;
}

0 template. f < int() >, 1.


funcPtrType temp1 = (funcPtrType)u.f; // taking func address
bool temp2 = !temp1;                  // temp2 == false
bool temp3 = temp2 < int();           // temp3 == false
bool temp4 = temp3 > (0);             // temp4 == false
return temp4;

A temp1 = u.template f < int() > (0);     // function call
funcPtrType temp2 = (funcPtrType) temp1;  // temp2 == 0
bool temp3 = !temp2;                      // temp3 == true
return temp3;

Note that temp2is a null pointer (created return T()). All different analysis, and both are valid! This is really necessary to disambiguate - that you need to insert a keyword template, if necessary.

0
source

All Articles