Reputation: 19473
Can I overload the std::string constructor?
I want to create a constructor which takes std::wstring and return a std::string. is it possible and how?
Thanks.
Upvotes: 3
Views: 2870
Reputation: 12710
This is not the Right True Way of doing it, and I think that I had smoked something when I coded this, but it solves the problem. Check the last function, `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 );
}
Upvotes: 0
Reputation: 79243
Rather define a free function:
std::string func(const std::wstring &)
{
}
Upvotes: 2
Reputation: 136515
Can I overload the std::string constructor?
Nope, it would require changing std::string
declaration.
I want to create a constructor which takes std::wstring and return a std::string. is it possible and how?
You can have a conversion function instead, like:
std::string to_string(std::wstring const& src);
However, you need to decide what to do with symbols that can't be represented using 8-bit encoding of std::string
: whether to convert them to multi-byte symbols or throw an exception. See wcsrtombs function.
Upvotes: 3
Reputation: 96311
No, you cannot add any new constructors to std::string
. What you can do is create a standalone conversion function:
std::string wstring_to_string(const wstring& input)
{
// Your logic to throw away data here.
}
If you (think you) want this to happen automatically, I strongly suggest re-evaluating that idea. You'll cause yourself a significant amount of headaches as wstring
s are automatically treated as string
when you least expect it.
Upvotes: 1