我有以下内容:
class Base
{
protected:
std::string _name;
public:
virtual ~Base(){}
const std::string &name;
Base()
: _name ("(no name)")
, name(_name)
{}
};
template <typename T>
class BaseH : public Base
{
public:
virtual ~BaseH() {}
BaseH() : Base() {}
T& operator~(){ ; return static_cast<T&>(*this);}
};
class One : public BaseH<One>
{
public:
One() : BaseH<One>() { _name = "One"; }
};
class Two
: public One
, public BaseH<Two>
{
public:
Two() : BaseH<Two>() { _name = "Two"; }
};
int main(int argc, char *argv[])
{
std::cout << Two().name << std::endl;
return 0;
}
我想从Two
和One
派生BaseH<Two>
,因为Two
是One
的特化,而operator~
是BaseH
必须始终返回调用它的对象类型的引用。
编译错误显然是:
In constructor ‘Two::Two()’:
error: reference to ‘_name’ is ambiguous
error: candidates are: std::string Base::_name
error: std::string Base::_name
In function ‘int main(int, char**)’:
error: request for member ‘name’ is ambiguous
error: candidates are: const string& Base::name
error: const string& Base::name
如何通过构造函数委派设置_name
引用,同时在name
和One
中访问Two
和const
?最干净的方法是什么?
答案 0 :(得分:3)
看起来你有diamond problem。你试过virtual inheritance吗?
e.g:
template <typename T>
class BaseH : virtual public Base
{
// ...
};
class One : virtual public BaseH<One>
{
// ...
};
编辑:在此处进一步阅读钻石问题:http://www.cprogramming.com/tutorial/virtual_inheritance.html