如何解决C ++中的多重继承歧义

时间:2017-12-10 03:05:34

标签: c++ templates inheritance methods ambiguous

我有一个小程序如下:

#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);
}

这不会编译,因为关于应该选择something()的两个可能版本中的哪一个存在歧义:

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]

我的问题是,如果我能编辑的唯一地方是use()的主体,我该如何解决这种歧义?

2 个答案:

答案 0 :(得分:4)

是。例如,您可以将调用限定为somethinggodbolt):

template <typename T>
bool use(T &t)
{
    return t.A::something();
}

答案 1 :(得分:1)

您可以为T派生自X的情况添加模板“use”的特化,然后将其强制转换为X.

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();
}

虽然必须检查语法,但这应该确保你在特殊情况下得到它,同时只允许一个“某事”调用。