Reputation: 13
Many consumers of the following class
class A{
double a;
void dump(){
std::ofstream ooo("dump.txt"); ooo << A.a << "\n"; ooo.close();
}
};
will not use dump
and cannot #include<fstream>
. How do I make it that A
still permits compilation by omission of void dump()
in that scenario.
What is the best practice to solving the problem?
I do not wish to change the signature of dump
.
I cannot use #ifdef
unless #include<fstream>
will make an according define
as per ISO.
A is a parent of many other classes. If I was to specialize from A then all derivatives would need a templatization of inheritance over A, appearing unpreferable.
ChatGPT proposes a requirement-dependent definition over the instantiability of std::ofstream
; however the definition of either case must remain written, thus causing a compilation error. I also do not see how to overcome the issue, as of my limited understanding of the language, I must at some point specify a definition and definition templates will be instantiated eventually, thus causing an instantiated invalid definition anyways. So I am lacking a piece of grammar or paradigm here, which is what I seek.
I encounter it first time, but in interpreted languages it is of course rather the norm than exception that definitions are invalid under most circumstances but those in which they are utilized.
Upvotes: -10
Views: 101
Reputation: 180145
The solution is extremely simple and meets all requirements. The consumers of the class use the header file:
class A{
double a;
void dump() ;
};
You write the .cpp file:
#include <fstream>
void A:: dump() {
std::ofstream ooo("dump.txt"); ooo << A.a << "\n"; ooo.close();
}
<fstream>
const
though)The linker takes care of including dump
if and when needed.
Upvotes: 2