I was writing some unit-tests when I stumbled upon a scenario that managed to bug me a couple of times already.
I need to generate some strings for testing a JSON writer object. Since the writer supports both UTF16 and UTF8 inputs, I want to test it with both.
Consider the following test:
class UTF8;
class UTF16;
template < typename String, typename SourceEncoding >
void writeJson(std::map<String, String> & data)
{
// Write to file
}
void generateStringData(std::map<std::string, std::string> & data)
{
data.emplace("Lorem", "Lorem Ipsum is simply dummy text of the printing and typesetting industry.");
data.emplace("Ipsum", "Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book");
data.emplace("Contrary", "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old");
}
void generateStringData(std::map<std::wstring, std::wstring> & data)
{
data.emplace(L"Lorem", L"Lorem Ipsum is simply dummy text of the printing and typesetting industry.");
data.emplace(L"Ipsum", L"Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book");
data.emplace(L"Contrary", L"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old");
}
template < typename String, typename SourceEncoding >
void testWriter() {
std::map<String, String> data;
generateStringData(data);
writeJson<String, SourceEncoding>(data);
}
int main() {
testWriter<std::string, UTF8>();
testWriter<std::wstring, UTF16>();
}
I manage to wrap everything nicely except for the duplicate generateStringData()
method. And I was wandering if it's possible to combine both generateStringData()
methods into a single one?
I know I could use a single method to generate strings in UTF8 and then use an additional method to convert the strings to UTF16, but I'm trying to find out if there's another way.
What have I considered/tried?
- Using
_T()
orTCHAR
or#ifdef UNICODE
won't help, since I need both flavors on the same platform that supports Unicode (e.g. Win >= 7) - Initializing
std::wstring
from something that is notL""
won't work since it expects a wchar_t - Initializing char by char won't work since it also requires
L''
- Using
""s
won't work since the return type depends on typecharT