是否可以用C++编写自定义转换运算符(如“static_cast”)

Is it possible to write custom cast operators in C++ (like `static_cast`)?

本文关键字:static cast 运算符 转换 C++ 自定义 是否      更新时间:2023-10-16

我得到了这个想法,并尝试编写一个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;
        }
};

我试着这样使用它:

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++中是不可能的,还是我的代码中缺少了什么?

您可以编写带有签名的免费函数:

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

看起来你只想要一个非成员函数,而不是一个函子:

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,您可以创建InSizeOutSize typedef s。

虽然我同意Jarod42的答案是更好的方法。出现错误的原因是,您试图在没有对象的情况下使用转换运算符。

string_cast<wchar_t>(AString)

是试图调用接受std::string&的c'tor。您的代码片段需要以下语法。

string_cast<wchar_t>()(AString)注意额外的一对(),它是对象创建。