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
5
  • 1
    It's invalid to put things into namespace std. AFAIK, the standard explicitly forbids it. Commented May 12, 2014 at 14:01
  • 1
    to be more specific abaout lethal-guitar: stackoverflow.com/questions/320798/… Commented May 12, 2014 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) Commented May 12, 2014 at 14:10
  • Regarding your 2nd question: this might help Commented May 12, 2014 at 14:44
  • Also: Why didn't you ask about boost from the start? The answer is very different for non-std classes Commented May 12, 2014 at 14:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.