I'm trying to compile with g++ some code previously developed under Visual C++ 2008 Express Edition, and it looks like g++ won't let me call a template method on a reference returned by a method of a template variable. I was able to narrow the problem down to the following code:
class Inner
{
public:
template<typename T>
T get() const
{
return static_cast<T>(value_);
};
private:
int value_;
};
class Outer
{
public:
Inner const& get_inner() { return inner_; };
private:
Inner inner_;
};
template<typename T>
int do_outer(T& val)
{
return val.get_inner().get<int>();
}
int main()
{
Outer outer;
do_outer(outer);
return 0;
}
The code compiles fine under Microsoft's compiler, but g++ throws an error:
$ g++ -c main.cpp
main.cpp: In function ‘int do_outer(T&)’:
main.cpp:24: error: expected primary-expression before ‘int’
main.cpp:24: error: expected ‘;’ before ‘int’
main.cpp:24: error: expected unqualified-id before ‘>’ token
where line 24 refers to return val.get_inner().get<int>();
.
If I make do_outer
a normal method receiving an Outer
reference the code compiles. Making Inner::get()
a normal method also works. And making Inner::get()
return void and receive a template parameter also works because the int specifier below becomes needless, i.e.:
class Inner
{
public:
template<typename T>
void get(T& val) const
{
val = static_cast<T>(value_);
};
private:
int value_;
};
...
template<typename T>
int do_outer(T& val)
{
int i;
val.get_inner().get(i);
return i;
}
...
(g++ doesn't complaing about the code above.)
Now I'm out of ideas. What's the problem? Is there a problem with gcc/g++? Is there a compliance issue with my code?
The compiler I'm using is:
$ g++ --version
g++ (Ubuntu 4.3.3-5ubuntu4) 4.3.3
could you try with?
template<typename T>
int do_outer(T& val)
{
return val.get_inner().template get<int>();
}
I don't have access to gcc atm, but I've had similar issues and adding the template keyword always solved them. And it works in VS too.