-1

I programmed a log class that logs messages in color in the terminal. I want it to be able to log anything I give it to log. I guess templates are the way to go. But can't i use auto as an argument type, then check if it is a string and if not call the tostring method of the object ?

Couroux
  • 67
  • 1
  • 5

3 Answers3

3

You could indeed use templates, then just add a template specialization for std::string that doesn't invoke std::to_string

#include <iostream>
#include <string>

template <typename T>
void ToLog(T t)
{
    std::cout << std::to_string(t) << '\n';
}

template <>
void ToLog<std::string>(std::string str)
{
    std::cout << str << '\n';
}

int main()
 {
    ToLog(5);
    ToLog(12.0);
    ToLog(std::string("hello"));
    return 0;
}

Output

5
12.000000
hello
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
3

Since c++20 you can use auto and overload for the other types you want to handle differently.

void log(auto test) {
  std::cout << std::to_string(test) << std::endl;
}

void log(const std::string &str) {
   std::cout << "str: " << str << std::endl;
}

int main()
{
    log(std::string("test"));
    log(10);
}
t.niese
  • 39,256
  • 9
  • 74
  • 101
2

No, auto needs to determine the type of a variable in compile time, which can't be done until C++20. If you are using C++ standard, either you use templates, preprocessor macros (as some logging libraries do) or directly some to_string function before passing the argument.

But, as said, with C++20 it can be done, and behaves like a template.

You might find this question useful.

Miguel
  • 2,130
  • 1
  • 11
  • 26
  • Thank you very much :) – Couroux Aug 18 '20 at 16:30
  • `auto determines the type of a variable in compile time` and why should that be a problem? And if it is a problem the how should templates solve that problem? – t.niese Aug 18 '20 at 16:35
  • @t.niese By the way the question was asked, it looked like the intention was to accept any argument and check its type dynamically. – Miguel Aug 18 '20 at 16:37
  • But how would a template help in that case? – t.niese Aug 18 '20 at 16:44
  • Well, it is the only way that you can make a function suitable for more than one type without using polymorphic classes and that works across all C++ standards, for what I know. – Miguel Aug 18 '20 at 16:47
  • But your answer reads the way that in the case when `auto` can be used as function argument (since c++20) that it won’t work in the given scenario. And not that `auto` can’t be used before c++20. – t.niese Aug 18 '20 at 16:59
  • It can also be read like that will give an error, but if it bugs you so much I'll just rephrase it. – Miguel Aug 18 '20 at 17:02