Attempting to use a template class inside of an optional i.e. std::optional<T>
as a function parameter for a templated function that does the following. If the std::optional<T> param
is truthy, then uses the <<
operartor to write param.value()
to a std::ostringstream
.
#include <iostream>
#include <sstream>
#include <optional>
#include <string>
template<typename T>
std::string send(int number, std::optional<T> param)
{
std::ostringstream oss;
oss << std::to_string(number);
if (param)
{
oss << " " << param.value();
}
return oss.str();
}
// Works just fine
// template<typename T>
// std::string send(int number, T param)
// {
// std::ostringstream oss;
// oss << std::to_string(number);
// if (param)
// {
// oss << " " << param;
// }
// return oss.str();
// }
int main()
{
std::cout << send(1, {3});
return 0;
}
However, the code above throws
error: no matching function for call to 'send'
note: candidate template ignored: couldn't infer template argument 'T' std::string send(int number, std::optional param)
Compiler command
clang++ main.cc --std=c++17
I don't quite understand why the compiler cannot infer the template argument here. Even when I specifically instantiate the template for a specific type as such.
template std::string send(int number, std::optional<int> param);