I want a function with has only 1 argument which is optional with generic type and has assigned boost::none as default value. Is that possible?
#include <iostream>
#include <string>
#include <boost/optional.hpp>
template <typename T>
void f(boost::optional<T> v = boost::none)
{
if (v)
{
std::cout<<"v has value: " << v.get();
}
else
{
std::cout<<"v has no value!";
}
}
int main()
{
f(12);
f("string");
return 0;
}
>Solution :
Yes, that’s possible, but it doesn’t work together with template deduction (f(12) will try to instantiate a f<int&&>, which doesn’t exist). Your code will compile when you call it like that:
f(boost::optional<int>{12});
or explicitly instantiate it:
f<int>(12);