Printing to stdout
is thread-safe in many systems when using printf
or std::cout
, but not in all systems (Windows!). So I decided to make my own thread-safe and type-safe printing function with some help of C++11 variadic templates functions.
#include <iostream>
#include <iomanip>
#include <mutex>
class Mutex:private std::mutex{
public:
class Lock:private std::lock_guard<std::mutex>{
public:
Lock(Mutex& mutex):
std::lock_guard<std::mutex>(mutex){}
};
};
class{
private:
Mutex m_mutex;
void Print(){}
template<typename T,typename... Ts>
void Print(const T& t,const Ts&... ts){
std::cout<<t<<std::flush;
Print(ts...);
}
public:
template<typename T,typename... Ts>
void operator()(const T& t,const Ts&... ts){
Mutex::Lock lock(m_mutex);
Print(t,ts...);
}
}Print;
template<typename T>
void PrintLine(){
Print('\n');
}
template<typename T,typename... Ts>
void PrintLine(const T& t,const Ts&... ts){
Print(t,ts...,'\n');
}
int main(){
Print(10," devided by ",3," equals ");
PrintLine(std::fixed,std::setprecision(5),10.0/3);
return 0;
}