0

Here is my simplestring class -- a template class which is supposed to deal with both char string and wchar_t string. I want to define a default_separator for both char string and wchar_t string:

When _Thar is char, default_separator is "\n" and when _Thar is wchar_t, default_separator is L"\n"

I define a MACRO DEFAULT_SEPARATOR as "\n", and I want to assign the value for both of the specilized member simplestring::default_separator and simplestring<wchar_t>::default_separator,

template<typename _TChar>
struct simplestring
{
#define DEFAULT_SEPARATOR "\n"

    static const _TChar* default_separator;

    void show_tstring()
    {
        throw "no implement";
    }
};

template<>
const char* simplestring<char>::default_separator = DEFAULT_SEPARATOR;
template<>
const wchar_t* simplestring<wchar_t>::default_separator = L##DEFAULT_SEPARATOR; //doesn't compile

void simplestring<char>::show_tstring()
{
    cout << "char string\n";
    cout << default_separator << endl;
}

void simplestring<wchar_t>::show_tstring()
{
    cout << "wchar_t string\n";
    wcout << default_separator << endl;
}

static void test()
{
    simplestring<char> s;
    s.show_tstring();

    simplestring<int> s2;
    s2.show_tstring();
}

The key line L##DEFAULT_SEPARATOR doesn't compile with error

Error C2014 preprocessor command must start as first nonwhite space ForTest

Zhang
  • 3,030
  • 2
  • 14
  • 31
  • Does this answer your question? [C++ preprocessor token pasting for namespace qualification](https://stackoverflow.com/questions/32252643/c-preprocessor-token-pasting-for-namespace-qualification) – Ulrich Eckhardt Nov 09 '20 at 06:14
  • 1
    `##` only works inside function-like `#define` directives and only with parameters of such directives, so you need to create a function-like macro just for `##`. In fact you need *two* layers of such macros, see e.g. https://stackoverflow.com/questions/8231966/why-do-i-need-double-layer-of-indirection-for-macros – n. m. could be an AI Nov 09 '20 at 06:30

1 Answers1

0

Thanks users above.

## only works behind #define, I made this worked,

#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
template<>
const wchar_t* simplestring<wchar_t>::default_separator = WIDEN(DEFAULT_SEPARATOR);

Actually I finally used this,

#ifdef _T
    template<>
    const wchar_t* ClipOprByLineT<wchar_t>::default_separator = 
    _T(DEFAULT_SEPARATOR);
#else
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
    template<>
    const wchar_t* ClipOprByLineT<wchar_t>::default_separator = 
    WIDEN(DEFAULT_SEPARATOR);
#endif
Zhang
  • 3,030
  • 2
  • 14
  • 31