加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

是否可以在C中编写自定义转换运算符(如`static_cast`)?

发布时间:2020-12-16 10:12:18 所属栏目:百科 来源:网络整理
导读:我得到了这个想法并尝试编写一个string_cast强制转换运算符来在C字符串之间进行转换. template class OutputCharTypeclass string_cast{ public: template class InputCharType operator std::basic_stringOutputCharType(const std::basic_stringInputCharT
我得到了这个想法并尝试编写一个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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读