Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template function passed to shared library (c++)

Bit of a thought experiment... Ingredient 1: A class in a (precompiled) shared library that has a function that takes a pointer to an object derived from ostream:

void ClassName::SetDefaultStream(std::ostream *stream)

Ingredient 2:

My own class deriving from std::ostream, with some generic templated stream operator:

class MyStream : public std::ostream
{
   public:
      template <typename T> MyStream &operator<<(const T &data)
      {
         std::cout << data;
         return *this;
      }
}

Now, if I pass the address of an instantiation of this class into the SetDefaultStream method, what will happen? At compile time, the compiler has no idea what types will be applied to the stream in the shared class, so surely no code will be synthesised? Will it fail to compile, will it compile and then crash when run, will smoke come out of the computer?

like image 709
user23167 Avatar asked May 05 '26 12:05

user23167


2 Answers

Your templated memmber won't be visible inside the library, since it isn't a virtual member of the base std::ostream. No problems will occur.

like image 128
David Norman Avatar answered May 08 '26 00:05

David Norman


it will compile but your operator will not be called.

like image 33
Maurice Perry Avatar answered May 08 '26 01:05

Maurice Perry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!