![](/img/trans.png)
[英]Overloading the << operator for a Pair of <std::string, std::Set>
[英]Overloading std::string constructor
我可以重载std :: string构造函数吗?
我想创建一个使用std :: wstring并返回std :: string的构造函数。 有可能吗?
谢谢。
我可以重载std :: string构造函数吗?
不,这将需要更改std::string
声明。
我想创建一个使用std :: wstring并返回std :: string的构造函数。 有可能吗?
您可以改用转换功能,例如:
std::string to_string(std::wstring const& src);
但是,您需要决定如何处理无法使用std::string
8位编码表示的符号:是将其转换为多字节符号还是引发异常。 请参阅wcsrtombs函数。
而是定义一个自由函数:
std::string func(const std::wstring &)
{
}
不,您不能向std::string
添加任何新的构造函数。 您可以做的是创建一个独立的转换函数:
std::string wstring_to_string(const wstring& input)
{
// Your logic to throw away data here.
}
如果您(认为您)希望这种情况自动发生,我强烈建议您重新评估该想法。 wstring
会在您最不期望的情况下自动视为string
,因此您会感到头痛。
这不是正确的正确方法,我认为我在编码时已经抽了些东西,但是可以解决问题。 检查最后一个函数“ convert_str”。
#pragma once
#include <memory>
#include <string>
#include <vector>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/logical.hpp>
template <typename Target, typename Source, typename cond>
struct uni_convert {
};
template <typename Target, typename Source >
struct uni_convert<Target,Source,
typename boost::enable_if< boost::is_same<Target, Source>, int >::type > {
static Target doit(Source const& src)
{
return src;
}
};
template <typename Cond >
struct uni_convert<std::string,std::wstring,
Cond > {
static std::string doit(std::wstring const& src)
{
std::vector<char> space(src.size()*2, 0);
wcstombs( &(*( space.begin() )), src.c_str(), src.size()*2 );
std::string result( &(*( space.begin() )) );
return result;
}
};
template <typename Cond >
struct uni_convert<std::wstring,std::string,
Cond > {
static std::wstring doit(std::string const& src)
{
std::vector<wchar_t> space(src.size()*2, 0);
mbstowcs( &(*( space.begin() )), src.c_str(), src.size()*2 );
std::wstring result( &(*( space.begin() )) );
return result;
}
};
template< typename TargetChar >
std::basic_string< TargetChar > convert_str( std::string const& arg)
{
typedef std::basic_string< TargetChar > result_t;
typedef uni_convert< result_t, std::string, int > convertor_t;
return convertor_t::doit( arg );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.