|
10鱼币
做了一个转换类, 但是比如说是字符串 中间有空格 就会在空格前截断, 但是如果不用模板类声明 w/stringstream 就是正常的
- //根据数据类型 自动选择 stream 的类型是 stringstream 还是 wstringstream
- //比如说函数的返回值是wstring, CStringW, wchar_t*, 那么 stream的类型应该是wstringstream
- // 那么否则 是string CStringA, char* stream的类型应该是stringstream
- #include <string>
- #include <iostream>
- #include <sstream>
- template<typename T>
- struct convert_string {
- typedef std::stringstream type;
- };
- template<>
- struct convert_string<wchar_t*> {
- typedef std::wstringstream type;
- };
- template<>
- struct convert_string<const wchar_t*> {
- typedef std::wstringstream type;
- };
- template<>
- struct convert_string<std::wstring > {
- typedef std::wstringstream type;
- };
- template<>
- struct convert_string<const std::wstring > {
- typedef std::wstringstream type;
- };
- template <typename TRet, typename TParam>
- inline TRet Convert(const TParam& t)
- {
- typename convert_string<TRet>::type stream;
- TRet tRet;
- stream << t;
- stream >> tRet;
- return tRet;
- }
- int main()
- {
- using namespace std;
- const char* pmsg = "hello world";
- std::stringstream a;
- std::wstringstream b;
- auto ret = Convert<std::string, const char*>(pmsg);
- auto nex = Convert<std::wstring>(L"WH AT");
- std::cout << ret;
- Convert<string>("12 34");
- Convert<string>("hello world");
- Convert<string>(L"1234");
- Convert<int>("1234");
- Convert<int>(L"1234");
- Convert<wstring>("2234");
- Convert<wstring>(L"1234");
- Convert<string>(3.15);
- Convert<wstring>(L"1234");
- return 0;
- }
复制代码 |
|