【问题标题】:Instantiating a templated class from a templated member function of a not templated class从非模板类的模板成员函数实例化模板类
【发布时间】:2015-08-10 14:52:44
【问题描述】:

我一直在尝试理解 boost::any 代码的工作原理,并尝试编写以下代码

class placeholder
{
public:
  virtual ~placeholder() {}
  virtual placeholder* clone() const=0;
};
//And this is the wrapper class template:

template<typename ValueType>
class holder : public placeholder
{
public:
  holder(ValueType const & value) : held(value) {}
  virtual placeholder* clone() const
  {return new holder(held);}

private:
  ValueType held;
};

//The actual type erasing class any is a handle class that holds a pointer to the abstract base class:

class any
{
  public:

    any() : content(NULL) {}

    template<typename ValueType>
      any( const ValueType  & value): content(new holder(value)) {}


    ~any()
    {delete content;}

    // Implement swap as swapping placeholder pointers, assignment
    // as copy and swap.

  private:
    placeholder* content;
};

int main( int argc, char ** argv ) {

  return 0;
}

当我尝试编译代码时,出现以下错误:

test.cxx: In constructor 'any::any(const ValueType&)':
test.cxx:33: error: expected type-specifier before 'holder'
test.cxx:33: error: expected ')' before 'holder'

上面的错误出现在该行

any( const ValueType  & value): content(new holder(value)) {}

我真的不明白为什么这里不能推断出类型。我读了Why can I not call templated method of templated class from a templated function 但无法解决我的问题

有人可以帮忙吗。

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    由于holder是模板而C++是not deduce template parameters based on the constructor,所以在any的构造函数中实例化模板参数时必须指定模板参数。

    template <typename ValueType>
    any( const ValueType  & value): content(new holder<ValueType>(value)) {}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多