类成员方法 - 返回类型模板



是否可以在 C++11 中以某种干净的方式执行此操作

class Foo 
{
   public:
     Foo(Bar1 * b1, Bar2 * b2) : bar1(b1), bar2(b2) {}
     template <typename T> T * GetData<T>();
   private:
      Bar1 * bar1;
      Bar2 * bar2;
};
template <> Bar1 * Foo::GetData<Bar1>() { return this->bar1;}
template <> Bar2 * Foo::GetData<Bar2>() { return this->bar2;}

在主代码中

Foo * foo = new Foo(new Bar1(), new Bar2());
Bar1 * b1 = foo->GetData<Bar1>();
Bar2 * b2 = foo->GetData<Bar2>();

这样做,它不会编译。

删除模板成员声明中的<T>

 template <typename T>  T* GetData();

而不是:

 template <typename T>  T* GetData<T>();

相关内容

最新更新