1

违规代码:

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 使模板类运行起来。

4

1 回答 1

2

当你说:

typedef boost::intrusive_ptr<T> Pointer;

当模板在您的代码中被实例化时,您正在声明一个类型,该类型是指向 a 的侵入式指针int(因为那时T是 a )。int您的 SharedObject 类不是int,因此您不能使用this.

编辑:好的,我误解了你的代码,我会再试一次。在:

return Pointer(this); //Ambiguous call here

根据错误消息,这是一个 SharedObject ,但是我认为指针的类型定义为 SomeClass 。

您的代码非常难以理解 - 无论您尝试做什么,都必须有一种更简单的方法。而且您似乎在基类中缺少一个虚拟析构函数(可能还有一个虚拟函数)。

于 2010-01-22T10:26:56.723 回答