问题
What I am trying to get at is a function that generates an instance of a CStringT<> that is appropriate for a given type of character (char or wchar_t).
Here's a contrived example:
#include <atlstr.h>
template <typename CHAR_T>
inline
CStringT< CHAR_T, ATL::StrTraitATL< CHAR_T, ATL::ChTraitsCRT< CHAR_T > > >
AsCString(const CHAR_T * psz)
{
return CStringT< CHAR_T, ATL::StrTraitATL< CHAR_T, ATL::ChTraitsCRT< CHAR_T > > >(psz);
}
I can certainly use the above (it appears to compile), but it would be a lot nicer for readers of my code (and probably for future compatibility) if I could use something like:
ATL::make_cstring(psz);
Is anyone aware of such a utility, or anything like it?
回答1:
It's already there, use either CString (project setting), CStringA or CStringW. After 17+ years of Unicode and operating systems that are exclusively Unicode, there are very few reasons left to avoid getting the project setting right.
回答2:
Lets see if I understand it correctly, you want to create a string based on the type of char (char /Wchar_t)
template <typename _T>
CStringT <_T, ATL::StrTraitATL <_T, ATL::ChTraitsCRT <_T > > >
make_cstring (_T* __args)
{
.. create cstring and return it
}
回答3:
Thank You, everyone who helped out with this.
Here is the answer that most completely answers my needs:
// generates the correct CString type based on char_T
template <typename charT>
struct cstring_type
{
// compile time error if no matching CStringT<> for charT
};
template <>
struct cstring_type<char>
{
typedef CStringA type;
};
template <>
struct cstring_type<wchar_t>
{
typedef CStringW type;
};
#define CSTRINGTYPE(T) typename cstring_type<T>::type
// returns an instance of a CStringA or CStringW based on the given char_T
template <typename charT>
inline CSTRINGTYPE(charT) make_cstring(const charT * psz)
{
return psz;
}
As you can see, it fully generates the correct CString type (either CStringA or CStringW) based entirely upon the template parameter (charT). This version has the added advantage of not trying to explicitly generate a CStringT<...> which depends on further compile time options (such as using CRT, using MFC, etc.). Instead, it results in the system-supplied CStringA or CStringW, which Microsoft maintains, hence giving my code greater flexibility and future-proofing it (as much as can be gained, I expect).
回答4:
Don't use all caps for non-macro purposes.
Why not just stick it in the ATL namespace and call it make_cstring? (hell, why not just use std::string?)
来源:https://stackoverflow.com/questions/4261418/is-there-a-better-way-to-declare-a-char-type-appropriate-instance-of-a-cstringt