0

in my code, I want to implement a function that prints any data type to console. the function always receives a string as the first argument and a data which can vary each time as the second argument.

Mutex_Loggers.h

namespace Loggers
{
    std::mutex m_mutex;
    template<typename T>
    void sharedLog(const std::string& message, T data)
    {
        std::lock_guard<std::mutex> locker(m_mutex);
        std::cout << message << data << std::endl;
    }
}

and one of the files which calls it like e.g. main.cpp

#include "Mutex_Loggers.h"
/*other stuff*/
Loggers::sharedLog("IN THREAD: ", std::this_thread::get_id());
Loggers::sharedLog("IN APP CREATION ", nullptr);
Loggers::sharedLog("IN create_CtrApp_and_register ", {1,2,3});

at compile time I get these errors:

C2593 operator << is ambiguous

C2679 binary << no operator found which takes a right-hand operand of type T (or there is no acceptable conversion)

How can I have function that prints any type of data

Amir-Mousavi
  • 4,273
  • 12
  • 70
  • 123

1 Answers1

3

The problem is that you are calling operator<< for types which don't overload that operator which you then call inside your sharedLog function.

In order to write an instance of type T to an std::ostream in this manner, you need to overload operator<<.

The operator should be implemented outside of T type, and it would have following signature:

std::ostream& operator<< (std::ostream &out, const T& arg);

If it needs to access private and protected members of T, it should be also declared as friend:

friend std::ostream& operator<< (std::ostream &out, const T& arg);

It should return the out reference it receives as the first arguments so that calls can be chained:

str << a << b << c;

You can find more details here: https://www.learncpp.com/cpp-tutorial/93-overloading-the-io-operators/

C2593 operator << is ambiguous

You have 2 or more implementations which are both candidates, and compiler doesn't know which one to pick. The error message contains additional details which point to the candidates so you can see which are the clashing types. See more here: error C2593: 'operator <<' is ambiguous

C2679 binary << no operator found which takes a right-hand operand of type T (or there is no acceptable conversion)

You are calling operator<< for type which doesn't overload it, as described at the beginning of my answer.

Zdeslav Vojkovic
  • 14,391
  • 32
  • 45