0

I have a function which returns a type std::istringstream inside one of my classes. To avoid #include <sstream> in my header file, I wrote the prototype class istringstream; at the top of my header file and wrote the return type as istringstream. When defining the function in my cpp file, I wrote the return type as std::istringstream.

I now have ambiguity issues where I am unable to use istringstream without declaring it as std::istringstream, although I have using std::istringstream.

What is the best practice here? I had always learned to declare prototypes instead of including the full header when possible.

Here is an example for clarity:

example.h

class istringstream;

istringstream myFunction();

example.cpp

#include "example.h"
using std::istringstream;

std::istringstream myFunction(){} // istringstream is ambiguous

Update:

Answered in comments -> it is not recommended to forward declare and is in fact undefined behavior.

user18348324
  • 244
  • 10
  • 1
    You can not make C++ standard library classes opaque so what you are trying to do seems pointless. – Öö Tiib Dec 27 '22 at 02:02
  • I'd just always learned to avoid including headers when possible and declaring prototypes instead @ÖöTiib . Is that not possible here? – user18348324 Dec 27 '22 at 02:03
  • `class istringstream;` is not a prototype, it is a forward declaration. It appears to be for something in the global namespace that you are promising to write, not for std::istringstream. – Avi Berger Dec 27 '22 at 02:05
  • Is there any way to declare prototypes for `std::object` ? @AviBerger – user18348324 Dec 27 '22 at 02:07
  • 6
    It is advised opposite, include always all standard library headers that you use. Besides std::istringstream is not class but typedef of instantiation of std::basic_istringstream template. – Öö Tiib Dec 27 '22 at 02:11
  • 3
    C++ Standard prohibits forward declaration of anything in the `std` namespace, see [here](https://stackoverflow.com/a/10290176/767632). So while it may work on a compiler of your choice, it may break at a whim. Or not. – yeputons Dec 27 '22 at 02:15
  • @user18348324 — there is no `std::object`. – Pete Becker Dec 27 '22 at 02:54
  • @PeteBecker I used `object` as a placeholder for ... any object. – user18348324 Dec 27 '22 at 03:01

0 Answers0