0

I have a template function in .hpp file:

class Wrapper {
 public:
     ...
     template <typename T>
     void PutIntoStream(T &&input);
};
void Wrapper::PutIntoStream(T &&input) {/*implementation*/}

In my .cpp file this function is specialized:

template<>
void Wrapper::PutIntoStream(const int &input)
{}

template<>
void Wrapper::PutIntoStream(const std::string &input)
{}

But then I'm trying to run specializations the template function is run:

int val{0};
std::string s{"Val"};

PutIntoStream(val); // template <typename T> void PutIntoStream(T &&input)
PutIntoStream(s);   // is called in both cases

Can anyone tell me what's the problem and how to fix it?

ivoriik
  • 155
  • 1
  • 11
  • 4
    Nobody outside of your `.cpp` file knows anything about the specializations in the `.cpp` files. Did you try explicitly declaring a specialization in the header file? – Sam Varshavchik Nov 23 '21 at 21:33
  • Perhaps there's some confusion between _template instantiation_ (which can be in a cpp file) and _template specialization_ (which must be visible to code that's expected to use it) – Drew Dormann Nov 23 '21 at 21:37
  • 1
    Unrelated to the issue but rather to the title of your question : no function here is specialized to handle specifically rvalue references. Your first specialization (T&&) is a universal reference (or forwarding reference). More info https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers – trialNerror Nov 23 '21 at 21:42
  • because templates can only be implemented in the header unless you follow some special means which you you do not, see [this](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – muaz Nov 23 '21 at 22:18
  • After an hour with no feedback, I'm inclined to close this as a duplicate of [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Drew Dormann Nov 23 '21 at 22:45

0 Answers0