Re: Create Generic Class with String?
On 12 apr, 22:40, Immortal Nephi <Immortal_Ne...@hotmail.com> wrote:
I create generic class. The type T is to be std::strin=
g or
std::wstring. I declare t variable to static const because I do not
want to modify string. C++ Compiler complies without errors.
If you add std::cout to the main function body, then C++ =
Compiler
will fail to compile and the error message says
c:\my projects\colors\colors\main.cpp(1438) : error C2373: 't' :
redefinition; different type modifiers
c:\my projects\colors\colors\main.cpp(1434) : see declara=
tion
of 't'
c:\my projects\colors\colors\main.cpp(1438) : while compi=
ling
class template static data member 'const std::string Foo<T>::t'
with
[
T=std::string
]
c:\my projects\colors\colors\main.cpp(1444) : see referen=
ce to
class template instantiation 'Foo<T>' being compiled
with
[
T=std::string
]
template< typename T >
class Foo
{
public:
Foo<T>() {}
~Foo<T>() {}
static const T t;
};
template< typename T >
T Foo<T>::t = "Hello World!\n";
int main()
{
Foo<std::string> f;
std::cout << f.t;
return 0;
}
What happen if I declare std::wstring instead of std::str=
ing? C++
Compiler will fail to compile because =91L' is not added before string
=94Hello World!\n=94.
I do not want to create two separate classes. One is f=
or string and
another one is for wstring. I add preprocessor condition.
#if !defined( UNICODE )
template< typename T >
std::string Foo<T>::Text = "Hello World!\n";
#else
template< typename T >
std::wstring Foo<T>::wText = L"Hello World!\n";
#endif
Do you have the solution?
Yes, you need std::wcout to << std::wstring.
Generally, it is bad idea to slice your code with preprocessor like
that. Better stick with explicit wchar_t or char. Microsoft has done
that thing with their TCHAR and despite tremendous manpower that
company has their solution outright leaks memory, looks like crap and
is very inefficient when compiled without unicode character set.