Dylan Nicholson schrieb:
Been playing around with this all day, and haven't found a solution I
like yet.
Assuming some initial function:
void foo(std::string& src)
{
src += "some fixed string";
src += bar();
src += "some other fixed string";
src += bar2();
src += "final fixed string";
}
What is the best way to turn this into a templated version that can
work on both std::basic_string<char> AND std::basic_string<wchar_t>?
Another possible solution (maybe clearer than my previous one, because
less code duplication):
#include <cstring>
#include <string>
#include <algorithm>
char const* bar();
char const* bar2();
template <typename charT, class traitsT, class allocatorT>
struct string_converter;
template <class traitsT, class allocatorT>
struct string_converter<char, traitsT, allocatorT>
{
static std::basic_string<char, traitsT, allocatorT> convert(char const*
String)
{
return std::basic_string<char, traitsT, allocatorT>(String);
}
};
template <class traitsT, class allocatorT>
struct string_converter<wchar_t, traitsT, allocatorT>
{
static std::basic_string<wchar_t, traitsT, allocatorT> convert(char
const* String)
{
std::basic_string<wchar_t, traitsT, allocatorT> ReturnValue;
std::size_t const StringLength(std::strlen(String));
ReturnValue.reserve(StringLength);
std::copy(String, String + StringLength,
std::back_inserter(ReturnValue));
return ReturnValue;
}
};
template <typename charT, class traitsT, class allocatorT>
void foo(std::basic_string<charT, traitsT, allocatorT>& src)
{
typedef string_converter<charT, traitsT, allocatorT> sc;
src += sc::convert("some fixed string");
src += sc::convert(bar());
src += sc::convert("some other fixed string");
src += sc::convert(bar2());
src += sc::convert("final fixed string");
}
int main()
{
std::basic_string<char> String1;
foo(String1);
std::basic_string<wchar_t> String2;
foo(String2);
}
hope this helps.
regards,
Thomas
[ See
http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]