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

Instantiating a templated class from a templated member function of a not templated class

本文关键字:函数 实例化 成员      更新时间:2023-10-16

我一直在尝试理解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)) {}

我真的不明白为什么不能在这里推断出类型。我读了为什么我不能从模板化函数调用模板化类的模板化方法,但是无法解决我的问题

谁来帮帮我。

由于holder是模板,而c++不根据构造函数推导模板参数,因此在any的构造函数中实例化模板参数时必须指定模板参数。

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