problem with templates and inheritance

I

Ivan Riis Nielsen

Hello group,

I've just stumbled upon a compile-error which I don't understand. I was
hoping someone can explain to me why my code is a problem.

I'm implementing a somewhat complex class hierarchy for a hobby project,
and I need to repeat it with several value types. So, I chose to
express it with templates. Here is sample code that demonstrates the
problem:

// code start
template <typename T>
class base {
T m_val;
public:
base(T init) : m_val(init) {}
T val() { return m_val; }
};

template <typename T>
class derived : public base<T> {
public:
derived(T init) : base<T>(init) {}

// adding this causes compile error:
T val(T x) { return x; }

// and this fixes it again
// T val() { return base<T>::val(); }
};

int main(void) {
derived<int> d(1);
int i=d.val();
return 0;
}
// code end

When I try to invoke val() (the no-args variant defined in the base
class base<T>) on a derived<T> object, and derived<T> defines a val(T x)
(with args). Removing this val(T x) from derived<T> also removes the
compile error. Compile error looks like this:

t.cc: In function `int main()':
t.cc:24: error: no matching function for call to `derived<int>::val()'
t.cc:16: note: candidates are: T derived<T>::val(T) [with T = int]

I'm using g++ 3.4.1.

Thanks
Ivan
 
I

Ivan Riis Nielsen

Max said:

Thanks a lot for the pointer. So, it wasn't template related at all...
In my simplistic mind, anything defined public in a public base classes
would carry the same weight as things defined locally, and then the
compiler could just choose the one which best matches the actual
argument given in a call. But the "using" trick is a quite small
effort, and a new word in my vocabulary:)

Ivan
 

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

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top