user23311233
user23311233

Reputation: 13

SFINAE-kindish function definition BUT without templates

Example

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.

Question

What is the best practice to solving the problem?

Constraints

Attempts

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.

Remarks

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

Answers (1)

MSalters
MSalters

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();
}
  • Header compiles without <fstream>
  • No templates
  • No #ifdef
  • Signature doesn't change (Still missing const though)

The linker takes care of including dump if and when needed.

Upvotes: 2

Related Questions