简体   繁体   中英

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?

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.

它会编译,但不会调用您的运算符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM