user23167
user23167

Reputation: 487

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?

Upvotes: 2

Views: 479

Answers (2)

Maurice Perry
Maurice Perry

Reputation: 32831

it will compile but your operator will not be called.

Upvotes: 3

David Norman
David Norman

Reputation: 19879

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.

Upvotes: 6

Related Questions