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'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