Picking correct function depending on return type
Hello!
I have an interesting problem, I want to pick the correct string-conversion
routine depending on what the return type is going to be. For example, I
have a typedef tstring like this:
#if defined(_UNICODE)
typedef std::wstring tstring;
#else
typedef std::string tstring;
#endif
Now I would like to have conversion routines that convert from
std::string/std::wstring to tstring. I already have routines that convert
from std::string to std::wstring and vice versa, so all that is needed is
to pick the correct method, depending on the _UNICODE macro. But I thought
it would be nicer to select the conversion routines depending on what type
tstring currently is. Here is my attempt:
#include <string>
#if 1
typedef std::wstring tstring;
#else
typedef std::string tstring;
#endif
// conversion routines
std::string wstring2string(const std::wstring& src);
std::wstring string2wstring(const std::string& src);
// conversion routine picker templates
template<class T>
struct tstring_type
{};
// specialization if tstring is std::string
template<>
struct tstring_type<std::string>
{
static tstring string2tstring(const std::string& src)
{
return src;
}
static tstring wstring2tstring(const std::wstring& src)
{
return wstring2string(src);
}
};
// specialization if tstring is std::wstring
template<>
struct tstring_type<std::wstring>
{
static tstring string2tstring(const std::string& src)
{
return string2wstring(src);
}
static tstring wstring2tstring(const std::wstring& src)
{
return src;
}
};
// convert string to tstring
tstring string2tstring(const std::string& src)
{
return tstring_type<tstring>::string2tstring(src);
}
int main()
{
using namespace std;
string str("Daniel");
string2tstring(str);
return 0;
}
Is there some way to do this without involving the _UNICODE macro anywhere
else than to define tstring? Any ideas?
Thanks in advance!
--
Daniel
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?