0
My job len() in C++ can return the size of std::string and of std::vector<std::string> but cannot return the size of const char *, 'Cause for that or I’d have to use strlen() or convert const char * for std::string to use the method size. I couldn’t change the flow control with the if to check the type of data entered and redirect to the treatment as it would be easy in interpreted languages.
How to edit this function to return both the size of std::string and std::vector<std::string> as well as const char * in a very attractive way?
// Função len()
template < typename T >
int len( T args )
{
return args.size();
}
std::string a = "Ola Mundo!";
const char * b = "Ola Mundo!";
std::vector<std::string> c = {"Ola", "Mundo", "!"};
std::cout << len(a) << "\n"; // Retorna 10.
std::cout << len(b) << "\n"; // error: request for member 'size' in 'args', which is of non-class type 'const char*'
std::cout << len(c) << "\n"; // Retorna 3.
Are you using C++17? If you are, why didn’t you ask the question?
– Maniero