I have a function that is overloaded for many types. But my current problem is due to that (LWS here : lws) :
#include <iostream>
#include <string>
#include <sstream>
#include <type_traits>
// First version
template<typename T, class = typename std::enable_if<std::is_fundamental<T>::value>::type>
std::string f(const T& x)
{
return std::to_string(x);
}
// Second version
template<typename... T>
std::string f(const std::tuple<T...>& x)
{
return std::to_string(sizeof...(T)); // It's just an example here
}
// Third version
template<typename T, class = typename std::enable_if<!std::is_fundamental<T>::value>::type, class = void>
std::string f(const T& x)
{
std::ostringstream oss;
oss<<x;
return oss.str();
}
// Main
int main(int argc, char* argv[])
{
std::cout<<f(42)<<std::endl;
std::cout<<f(std::string("Hello World"))<<std::endl;
std::cout<<f(std::tuple<int, int, int, int, int, int>(4, 8, 15, 16, 23, 42))<<std::endl;
return 0;
}
My problem is that when we call f()
for a std::tuple
, the third version is executed and not the second one.
How to solve this problem (a solution would be to allow the third version only for types where <<
is defined, but I don't know how to do that, and if this is the best way to solve the problem) ?