2015-12-15 42 views
3

我明白了這個想法,並試圖編寫一個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++中,還是我失去了我的代碼的東西嗎?

+0

你'string_cast'類沒有默認的構造函數。所以它似乎沒有太多。 – StoryTeller

+2

看來你只是想在這裏不上課。 – Jarod42

回答

7

你可以寫自由函數簽名:

template <typename OutputCharType, typename InputCharType> 
std::basic_string<OutputCharType> 
string_cast(const std::basic_string<InputCharType>& InputString) 
3

看起來你只是想要一個非成員函數,而不是一個函子:

template <class OutputCharType, class InputCharType> 
std::basic_string<OutputCharType> 
string_cast(const std::basic_string<InputCharType> & InputString) 
{ 
    std::basic_string<OutputCharType> OutputString; 
    const auto LENGTH = InputString.length(); 
    OutputString.resize(LENGTH); 
    for (auto i=0; i<LENGTH; i++) 
    { 
     OutputString[i] = static_cast<OutputCharType>(OutputString[i]); 
    } 
    return OutputString; 
} 

另外請注意,我改變了size_type類型到auto。這是因爲它們依賴的名字,所以你需要使用typename使用它們作爲類型(MSVC可能讓你得逞的,沒有它,但這是不可移植):

const std::basic_string<InputCharType>::size_type LENGTH = InputString.length(); 
//change to 
const typename std::basic_string<InputCharType>::size_type LENGTH = InputString.length();  
// ^^^^^^^^ 

這變得很醜陋,所以最好只使用auto。如果您不能使用C++ 11,則可以創建InSizeOutSizetypedef s。

1

儘管我同意Jarod42的回答是更好的方法。您遇到錯誤的原因是,您嘗試使用沒有對象的轉換運算符。

是調用一個接受std::string&一個c'tor的嘗試。您的代碼段需要以下語法。

string_cast<wchar_t>()(AString)請注意多餘的一對(),這是對象創建。

相關問題