0

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
Sammy
  • 1,105
  • 2
  • 9
  • 10
  • 1
    It's invalid to put things into `namespace std`. AFAIK, the standard explicitly forbids it. – lethal-guitar May 12 '14 at 14:01
  • 1
    to be more specific abaout lethal-guitar: http://stackoverflow.com/questions/320798/adding-types-to-the-std-namespace – okaerin May 12 '14 at 14:04
  • I used std in the example to simplify, but i am really interesed in forward decalaring templatized boost log class (which has nested namespaces) – Sammy May 12 '14 at 14:10
  • Regarding your 2nd question: [this](http://stackoverflow.com/questions/3879162/how-to-forward-declare-a-template-class) might help – lethal-guitar May 12 '14 at 14:44
  • Also: Why didn't you ask about boost from the start? The answer is very different for non-std classes – lethal-guitar May 12 '14 at 14:46

2 Answers2

2

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.

lethal-guitar
  • 4,438
  • 1
  • 20
  • 40
1

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;
okaerin
  • 789
  • 5
  • 23