我明白了這個想法,並試圖編寫一個string_cast
轉換操作符來在C++字符串之間進行轉換。是否可以使用C++編寫自定義的轉換運算符(如`static_cast`)?
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;
}
};
我試圖用這樣的:
std::string AString("Hello world!");
std::cout << AString << std::endl;
std::wcout << string_cast<wchar_t>(AString) << std::endl; // ERROR
的錯誤信息是:
Error C2440 '<function-style-cast>': cannot convert from
'const std::string' to 'string_cast<wchar_t>'
這是不可能在C++中,還是我失去了我的代碼的東西嗎?
你'string_cast'類沒有默認的構造函數。所以它似乎沒有太多。 – StoryTeller
看來你只是想在這裏不上課。 – Jarod42