Reputation: 9688
I have a small program as follows:
#include <iostream>
template <typename T>
class X{
public:
bool something(){
return true;
}
};
class A: public X<A>{
};
class B: public A, public X<B>{
};
template <typename T>
bool use(T &t)
{
return t.something();
}
int main()
{
B b;
std::cout << "use returned: " << use(b);
}
This will not compile because there is an ambiguity as to which of the two possible versions of something()
should be selected:
In instantiation of 'bool use(T&) [with T = B]': 30:43: required from here 22:20: error: request for member 'something' is ambiguous 6:14: note: candidates are: bool X<T>::something() [with T = B] 6:14: note: bool X<T>::something() [with T = A] In function 'bool use(T&) [with T = B]': 23:1: warning: control reaches end of non-void function [-Wreturn-type]
My question is, how can I resolve this ambiguity if the only place I can edit is the body of use()
?
Upvotes: 2
Views: 567
Reputation: 3715
You could add a specialization of the template “use” for the case where T derives from X and then casts to X inside.
template <typename T>
class X{
public:
bool something(){
return true;
}
};
class A: public X<A>{
};
class B: public A, public X<B>{
};
#
# If class derives from X<T> make sure to cast to X<T> before calling something
#
template<typename T>
typename std::enable_if<std::is_base_of<X<T>, T>::value, bool>::type use(T &t)
{
return static_cast<X<T>&>(t).something();
}
#
# This gets run for everything that doesn't derive from X<T>
#
template<typename T>
typename std::enable_if<!std::is_base_of<X<T>, T>::value, bool>::type use(T &t)
{
return t.something();
}
Have to check the syntax though, but this should make sure you get it for your special case while allowing anything with only one “something” call.
Upvotes: 1