I defined my own string type in the code.
typedef wchar_t CharType;
typedef std::basic_string<CharType> StringType;
I have a static class (it won't have an instance) which will print string messages on the screen. I decided to put a COUT static member which will refer to std::cout or std::wcout according to the string type I defined.
Header:
#include <ostream>
class MyTestClass
{
public:
// ...
static std::basic_ostream<CharType> & COUT;
// ...
}
CPP:
std::basic_ostream<CharType> & MyTestClass::COUT = /* How do I initialize this? */;
Is there a way of initializing this static member COUT?
This is an option in C++17:
#include <iostream>
#include <type_traits>
template <class T>
auto &get_cout() {
if constexpr(std::is_same_v<T, char>){
return std::cout;
}else{
return std::wcout;
}
}
int main() {
{
using CharType = char;
std::basic_ostream<CharType> & MyTestClass_COUT = get_cout<CharType>();
MyTestClass_COUT << "Hello";
}
{
using CharType = wchar_t;
std::basic_ostream<CharType> & MyTestClass_COUT = get_cout<CharType>();
MyTestClass_COUT << L"World";
}
}
If you don't have C++17 you can replace if constexpr with a trait-based solution.
Demo.
Old fashioned trait style solution:
template<class T>
struct cout_trait {};
template<>
struct cout_trait<char> {
using type = decltype(std::cout);
static constexpr type& cout = std::cout;
static constexpr type& cerr = std::cerr;
static constexpr type& clog = std::clog;
};
template<>
struct cout_trait<wchar_t> {
using type = decltype(std::wcout);
static constexpr type& cout = std::wcout;
static constexpr type& cerr = std::wcerr;
static constexpr type& clog = std::wclog
};
Usage:
auto& cout = cout_trait<char>::cout;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With