Question

Why doesn't this work ?

//file1.hpp

#include <vector>
namespace std
{ 
   typedef vector<int> IntVec;
}

//file2.hpp
//forward declare IntVec

namespace std {
   class IntVec;
}

class MyClass {
    std::IntVec* myVec;
public:
     MyClass();
};

#include "file1.hpp"
//file2.cpp
MyClass::MyClass()
{
   myVec = new std::IntVec;
}

Visual studio errors with 'std::IntVec' redefinition, different basic types; no appropriate default constructor.

What I am interested in is forward declaring Boost severitly logger

//i want to do this so that I don't need to include boost log headers in my headers 
typedef boost::log::sources::severity_logger<SeverityLevel> MyLogger
Était-ce utile?

La solution

You cannot forward declare a typedef. Furthermore, you cannot forward declare std classes - you just have to include the relevant files in these cases (<iosfwd> is a notable exception, though).

So I don't think what you're trying to achieve here is possible. Just put your typedef in a header, and include that instead of a forward-declaration.

Btw.: Do not heap-allocate vector class members. A vector already takes care of heap-allocation internally. So having this:

class MyClass {
    IntVec myVec; // No pointer
};

Makes the constructor obsolete, since myVec is automatically default-constructed when you initialize a MyClass in this case.

Autres conseils

because your typedef and the class definition "collide" with each other. Besides you did not specify any default constructor for your class "IntVec" and you're trying to instantiate it with:

 myVec = new std::IntVec;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top