从未模板化类的模板化成员函数实例化模板化类

时间:2015-08-10 14:52:44

标签: c++ templates

我一直在尝试理解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然而无法解决我的问题

有人可以帮忙。

1 个答案:

答案 0 :(得分:2)

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

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