How to forward a declare class that is in an unnamed namespace

I am trying to create a class with lazy calculations. Therefore, I need a structure for storing previously calculated variables, and I want to put this class in an unnamed namespace (I don't want to pollute the global area). Here is the minimal code that explains what I want: calculator.h :

 #ifndef CALCULATOR_H #define CALCULATOR_H class PrevCalc; class Calculator { public: Calculator(); PrevCalc* prevCalc; }; #endif // CALCULATOR_H 

calculator.cpp :

 #include "calculator.h" namespace{ struct PrevCalc{ double prevA = -1; double prevB = -1; double prevC = -1; }; } Calculator::Calculator() { prevCalc = new PrevCalc(); } 

Of course, this gives the expected type-specifier before 'PrevCalc' , and if I define PrevCalc without a namespace, everything works fine. My question is how to declare a class to be defined in an unnamed namespace in a .cpp file

+7
c ++
source share
1 answer

My question is how to declare a class to be defined in an unnamed namespace in a .cpp file

You can not. The unnamed namespace is clearly intended for personal vision for the current translation unit in which it appears, and cannot be used for forward declarations inherently.

You should probably use the pimpl idiom if you want to hide implementation details.


Another popular approach is to use the internal_ namespace, and the document is not intended to be used by public :

 namespace calculators { namespace internal_ { struct PrevCalc{ double prevA = -1; double prevB = -1; double prevC = -1; }; } class Calculator { public: Calculator(); private: // !!!! internal_::PrevCalc* prevCalc; }; } 
+5
source share

All Articles