Reputation: 2802
I want to define template variables without a class, but MSVC++ does not accept it, and Googling around it seems to be incorrect according to the C++ standard:
template<CharType> static CharType hexDigits[17];
template<> char hexDigits[17] = "0123456789ABCDEF";
template<> wchar_t hexDigits[17] = L"0123456789ABCDEF";
These specialized variables will then be used from within a (non-specialized) template function.
So I'm forced to write it like this:
template<typename CharType> class dummyclass {
static CharType hexDigits[17];
};
template<> char dummyclass<char>::hexDigits[17] = "0123456789ABCDEF";
template<> wchar_t dummyclass<wchar_t>::hexDigits[17] = L"0123456789ABCDEF";
Is there any way I can define these two variables without defining a dummy class?
Also, is there any good reason why the C++ standard does not allow the first piece of code? After all, template functions outside a class are permitted.
Upvotes: 2
Views: 158
Reputation: 67723
Also, is there any good reason why the C++ standard does not allow the first piece of code? After all, template functions outside a class are permitted.
Note that this:
template<CharType> static CharType hexDigits[17];
template<> char hexDigits[17] = "0123456789ABCDEF";
template<> wchar_t hexDigits[17] = L"0123456789ABCDEF";
has two symbols with different types but the same name: this can't possibly work, so the compiler would have to start mangling/decorating the names of variables like it already does for functions and classes.
In terms of implementing this cleanly, this looks like a trait to me ... if you don't mind getting a link error instead of a compile error, you can even skip the specialization and only declare the appropriate static members:
template <typename CharType> struct my_char_traits {
static CharType hex_digits[17];
};
template<> char my_char_traits<char>::hex_digits[17] = "0123456789ABCDEF";
template<> wchar_t my_char_traits<wchar_t>::hex_digits[17] = L"0123456789ABCDEF";
Upvotes: 2
Reputation: 63190
You can only create a class template or struct or a function template.
Template variable's like you're trying to do is illegal in C++.
You'll have to create a class template and then use that.
Upvotes: 0