违规代码:
template<typename T>
class SharedObject {
public:
typedef boost::intrusive_ptr<T> Pointer;
typedef boost::intrusive_ptr<T const> ConstPointer;
inline Pointer GetPointer() {
return Pointer(this); //Ambiguous call here
}
inline ConstPointer GetPointer() const {
return ConstPointer(this);
}
...
并像这样使用:
template <typename T>
class SomeClass: public SharedObject<SomeClass<T> > {
public:
static inline boost::intrusive_ptr<SomeClass<T> > Create() {
return (new SomeClass)->GetPointer();
}
};
int main()
{
auto v = SomeClass<int>::Create();
}
带有 boost 1.41 的 GCC (4.4.1) 在初始化 GetPointer() 的第一个(非常量)版本时会出现此错误:
error: call of overloaded ‘intrusive_ptr SharedObject<SomeClass<int> >* const)’ is ambiguous
boost/smart_ptr/intrusive_ptr.hpp:118: note: candidates are: boost::intrusive_ptr<T>::intrusive_ptr(boost::intrusive_ptr<T>&&) [with T = SomeClass<int>] <near match>
boost/smart_ptr/intrusive_ptr.hpp:94: note: boost::intrusive_ptr<T>::intrusive_ptr(const boost::intrusive_ptr<T>&) [with T = SomeClass<int>] <near match>
boost/smart_ptr/intrusive_ptr.hpp:70: note: boost::intrusive_ptr<T>::intrusive_ptr(T*, bool) [with T = SomeClass<int>] <near match>
对于我在 C++ 中不那么神秘的技能,我根本不明白为什么会有任何歧义。第 188 行和第 94 行的两个候选对象采用现有的 intrusive_ptr 右值引用,SharedObject::this
当然不是。然而,最终的候选者是完美匹配的(bool 参数是可选的)。
有人愿意告诉我问题是什么吗?
编辑+回答:我终于意识到
inline Pointer GetPointer() {
return Pointer(this); //Ambiguous call here
}
this
指 SharedObject 而 Pointer typedef 是 SomeClass。(这几乎就是巴特沃思立即指出的)。
inline Pointer GetPointer() {
return Pointer(static_cast<C*>(this));
}
因为我知道this
它确实是 SomeClass,从 SharedObject 继承,所以 static_cast 使模板类运行起来。