Apr 24, 2020 at 6:08pm UTC
Is there a way to put all those in one function? If not, could I do so with a class?
Apr 24, 2020 at 6:09pm UTC
Probably could use constexpr if.
Apr 24, 2020 at 6:40pm UTC
Last edited on Apr 24, 2020 at 6:43pm UTC
Apr 24, 2020 at 7:27pm UTC
Use a stringstream:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
#include <string>
#include <sstream>
template <typename T>
int display(T value)
{
std::ostringstream ss{};
ss << value;
return ss.str().length();
}
int main()
{
std::cout << display(453) << std::endl;
std::cout << display(4.7632) << std::endl;
std::cout << display('c' ) << std::endl;
std::cout << display("asdfadsf" ) << std::endl;
std::cout << display(std::string("STR" )) << std::endl;
return 0;
}
Last edited on Apr 24, 2020 at 7:45pm UTC
Apr 24, 2020 at 7:31pm UTC
You could just do ss.str().length(), but yes I like that solution more. It makes it so that a << operator must be defined as opposed to a to_string function, which matches how streams are expected to work in most classes.
Last edited on Apr 24, 2020 at 7:31pm UTC
Apr 24, 2020 at 7:34pm UTC
@Ganado, Yeah I noticed that right after I posted it. I have edited my code now.
Last edited on Apr 24, 2020 at 7:37pm UTC