#include <type_traits>
#include <string>
template<typename StringType>
StringType test()
{
// Assign local immediately with string literal!
StringType local; // = ?
// This is current implementation that is not desired
// because it results in twice as much lines
ifconstexpr (std::is_base_of_v<std::basic_string<wchar_t>, StringType>)
{
local = L"wide string";
}
else
{
// This is where bloated portion begins...
local = "ansi string";
}
return local;
}
int main()
{
auto result = test<std::wstring>();
return 0;
}
For example I wan to say:
StringType local = "test string"; // or L"test string"
However this won't work if StringType is wide string, on another side if I prepend L then it won't work for ANSI string.
Note that this has nothing to do with compilation mode, ex whether UNICODE is defined, this function is called for both types of strings and I need to determine how to reduce reduce code by factor of 2.
Therefore macro isn't a solution, but rather some constexpr lambda or something.
What would be the most efficient method?
interesting -- I found several ways to do it that add a great deal more bloat, and absolutely nothing that was honestly shorter (you can make it slightly shorter and uglier, but not do less work or any cleaner).
Yeah, I was googling out as well and realized there is indeed no way.
What is possible is to make a string conversion function and then conditionally call it for wide strings.
This would remove bloat but it would also incur linear performance penalty, ex. depending on how many strings needs to be processed.