![](/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.