我得到了这个想法并尝试编写一个string_cast
转换运算符来在C++字符串之间进行转换.
template <class OutputCharType>
class string_cast
{
public:
template <class InputCharType>
operator std::basic_string<OutputCharType>(const std::basic_string<InputCharType> & InputString)
{
std::basic_string<OutputCharType> OutputString;
const std::basic_string<InputCharType>::size_type LENGTH = InputString.length();
OutputString.resize(LENGTH);
for (std::basic_string<OutputCharType>::size_type i=0; i<LENGTH; i++)
{
OutputString[i] = static_cast<OutputCharType>(OutputString[i]);
}
return OutputString;
}
};
Run Code Online (Sandbox Code Playgroud)
我试着像这样使用它:
std::string AString("Hello world!");
std::cout << AString << std::endl;
std::wcout << string_cast<wchar_t>(AString) << std::endl; // ERROR
Run Code Online (Sandbox Code Playgroud)
错误消息是:
Error C2440 '<function-style-cast>': cannot convert from
'const std::string' to 'string_cast<wchar_t>'
Run Code Online (Sandbox Code Playgroud)
这在C++中是不可能的,还是我在代码中遗漏了一些东西?
您可以使用签名编写免费功能:
template <typename OutputCharType, typename InputCharType>
std::basic_string<OutputCharType>
string_cast(const std::basic_string<InputCharType>& InputString)
Run Code Online (Sandbox Code Playgroud)