3

The following code does not compile, why is that? And how can I fix this?

struct A{
    template<int N> int get() { return N; }
};

template <typename X>
struct B : public X {
    template<int N> int get() {
        return X::get<N>();
    }
};

int main(int argc, const char *argv[])
{
    B<A> b;
    return b.get<5>();
}

Compiler error:

test.cxx: In member function ‘int B<X>::get()’:
test.cxx:8:30: error: expected primary-expression before ‘)’ token
test.cxx: In member function ‘int B<X>::get() [with int N = 5, X = A]’:
test.cxx:15:25:   instantiated from here
test.cxx:8:30: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to  binary ‘operator<’
ali_bahoo
  • 4,672
  • 6
  • 37
  • 62
Allan
  • 4,390
  • 7
  • 36
  • 55

1 Answers1

5

you must disambiguate it, like so:

template<int N>int get() {
    return X::template get<N>();
}
justin
  • 103,167
  • 13
  • 178
  • 224
  • Why is there a need of disambiguation? OP is strictly calling `X::get();` – ali_bahoo Jan 06 '12 at 08:21
  • 5
    @sad_man: Without instantiating X during the first pass, we don't know that `get` is a member template. `X::get()` is interpreted as `X::get less_than N greater_than ()` which is an error. – visitor Jan 06 '12 at 08:35
  • 4
    @sad_man: Basically C++ rules don't allow a situation where the same code could mean both a call to a member function template and a series of comparisons, depending on the specialization of X. (VC++ gets it wrong, AFAIK.) – visitor Jan 06 '12 at 08:41