2

I have been trying to understand the working of the code for boost::any and tried writing the following code

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;
}

When I try to compile the code I get the following error:

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

The error above appears in the line

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

I don't really understand why the type cannot be deduced here. I read Why can I not call templated method of templated class from a templated function however was not able to solve my problem

Can someone please help.

Community
  • 1
  • 1
deb
  • 631
  • 1
  • 5
  • 15

1 Answers1

2

Since holder is a template and C++ does not deduce template parameters based on the constructor, you must specify the template parameter when instantiating it in the constructor of any.

template <typename ValueType>
any( const ValueType  & value): content(new holder<ValueType>(value)) {}
Community
  • 1
  • 1
m.s.
  • 16,063
  • 7
  • 53
  • 88