2

I want to use the forward declaration for the ptree class of boost::property_tree.

I use Visual Studio 2010 and boost version 1.48.0.

I do the forward declaration in the following way, in my .h

#ifndef OPTIONS_H_
#define OPTIONS_H_

namespace boost
{
    namespace property_tree
    {
        class ptree;
    }
}

class Options
{
   // something

private:
    boost::property_tree::ptree *m_pxPropertyTree;
};

#endif // OPTIONS_H_

Then, I use the class inside my .cpp

#include <boost/property_tree/ptree.hpp>

using boost::property_tree::ptree;

Options::Options()
{
    m_pxPropertyTree = new ptree();

    // other stuff
}

when I try to compile it, I obtain the following error

error C2371: 'boost::property_tree::ptree': redefinition. Different base type. c:\lib\boost\1.48.0\32\boost\property_tree\ptree_fwd.hpp 95

(The error description can be different, I've translated it because I've the Italian version of Visual Studio).

The line that gives me the error, in ptree_fwd.hpp, is the following

typedef basic_ptree<std::string, std::string> ptree;

Instead, if I don't use the forward declaration, everything goes well and I compile it successfully.

What I'm doing wrong and how I can use correctly the forward declaration in this case?

Null
  • 1,950
  • 9
  • 30
  • 33
Jepessen
  • 11,744
  • 14
  • 82
  • 149
  • 1
    `ptree` is not a class, but a `typedef` (i.e. an alias of another type). This means when you try to forward declare it you do it as a class, and the class and and the typedef will clash. – Some programmer dude Feb 24 '12 at 15:40

1 Answers1

3

Why don't you just include boost/property_tree/ptree_fwd.hpp? This header contains all forward declaration for the package.

Edit: The solution without the included (which you want to avoid for good reasons) is to exactly match, what is actually declared.

So:

#include <string>
#include <functional>
namespace boost
{
  namespace property_tree
  {
    template < class Key, class Data, class KeyCompare >
    class basic_ptree;

    typedef basic_ptree< std::string, std::string, std::less<std::string> > ptree;
  }
}
pmr
  • 58,701
  • 10
  • 113
  • 156
  • If you don't have to include headers in headers, it's better that you don't. – Luchian Grigore Feb 24 '12 at 15:55
  • Because I'm more fast in compilation and I don't need to include those boost headers if someone else must use my library. – Jepessen Feb 24 '12 at 16:05
  • @LuchianGrigore True. It also looks like the header is pulling in some unneeded things likes `optional_fwd.hpp`. – pmr Feb 24 '12 at 16:09