Oleksandr N.
Oleksandr N.

Reputation: 33

Statiс variable in base templated class, C++17 usage

I use C++17 and I'm trying to make such classes hierarchy (simplified):

template<typename TChar>
class CLoggerTxtBase {
public:
    using TString = std::basic_string<TChar>;
    static TString _default_output_format;
};

using CLoggerTxt = CLoggerTxtBase<char>;
template<> std::basic_string<char> CLoggerTxt::_default_output_format{ "%F %T" };

using CLoggerWTxt = CLoggerTxtBase<wchar_t>;
template<> std::basic_string<wchar_t> CLoggerWTxt::_default_output_format{ L"%F %T" };

template<typename TChar> class CLoggerTxtFile {};
template<typename TChar> class CLoggerTxtCout {};

After this I have two functions that use both classes:

funct1(){
    CLoggerTxtCout<wchar_t> log;
}
funct2() {
    CLoggerTxtFile<wchar_t> log;
}

clang alerts linker errors:

duplicate symbol 'Logger::CLoggerTxtBase<wchar_t>::_default_output_format' in:
    CMakeFiles/test_logger.dir/src/logger_txt_file.cpp.o
    CMakeFiles/test_logger.dir/src/logger_txt_cout.cpp.o

I have no ideas how to make single _default_output_format instance for each CLoggerTxtBase instance... Because of template I don't use .CPP-files for classes hierarchy. It looks that it must be inlined somehow... Thanks in advance!

UPD My colleague gave me an idea to use static functions that return reference to string. It's a solution, but I still would like to know is it possible to use static variables with such manner.

Upvotes: 0

Views: 84

Answers (1)

Oleksandr N.
Oleksandr N.

Reputation: 33

Thanks to VTT. I tried code below :

using CLoggerTxt = CLoggerTxtBase<char>;
template<> inline std::basic_string<char> CLoggerTxt::_default_output_format{ "%F %T" };

using CLoggerWTxt = CLoggerTxtBase<wchar_t>;
template<> inline std::basic_string<wchar_t> CLoggerWTxt::_default_output_format{ L"%F %T" };

That's the correct C++17 solution.

Upvotes: 0

Related Questions