65.9K
CodeProject 正在变化。 阅读更多。
Home

STL字符串和流的TCHAR风格头文件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.90/5 (14投票s)

2006年2月12日

CPOL

1分钟阅读

viewsIcon

114197

downloadIcon

505

提供一个头文件,允许使用 STL 的单个源文件在 ANSI 或 Unicode 中构建,无需任何更改或大量 #ifdef 指令。

引言

我曾在 Visual C++ 论坛上询问是否有标准的头文件可以提供一种声明 std::string 的方法,以便单个代码源可以在 ANSI 或 UNICODE 构建中编译,而无需任何更改,就像 tchar.h 一样。我得到的回复是没有标准的方法来做到这一点,所以我决定编写自己的头文件来完成这项任务。

TSTL.H 头文件

这个头文件很简单,它使用一系列 typedef 来定义一些常用的使用 charwchar_t 的 STL 类的新的同义词。其想法是,现在你可以使用新的名称,而之前你可能需要使用标准名称中的一个或另一个。例如,一段代码可能被写成

#ifdef _UNICODE
   std::wostringstream stream;
   stream.setf(std::wios::fixed);
#else
   std::ostringstream stream;
   stream.setf(std::ios::fixed);
#endif

现在可以写成

std::tostringstream stream;
stream.setf(std::tios::fixed);

它将在 ANSI 或 Unicode 构建中编译。该文件可能不完整,因为可能还有其他 STL 类是我不知道或没有想到的,应该包含在这个文件中。如果有,请告诉我哪些,我可以包含它们并更新文件。

要使用该文件,只需将其包含在你的预编译头文件中 (stdafx.h) 或将其包含在任何使用 STL 字符串或流类的文件中。该文件在此处列出,可以从本文顶部的下载链接下载。

// tstl.h - header file for TCHAR equivalents of STL
//          string and stream classes
//
// Copyright (c) 2006 PJ Arends
//
// This file is provided "AS-IS". Use and/or abuse it
// in any way you feel fit.
// 
 
#pragma once

#include <string>
 
namespace std
{
#if defined UNICODE || defined _UNICODE
 
    typedef wstring         tstring;
 
    typedef wstringbuf      tstringbuf;
    typedef wstringstream   tstringstream;
    typedef wostringstream  tostringstream;
    typedef wistringstream  tistringstream;
 
    typedef wstreambuf      tstreambuf;
 
    typedef wistream        tistream;
    typedef wiostream       tiostream;
 
    typedef wostream        tostream;
 
    typedef wfilebuf        tfilebuf;
    typedef wfstream        tfstream;
    typedef wifstream       tifstream;
    typedef wofstream       tofstream;
 
    typedef wios            tios;
 
#   define tcerr            wcerr
#   define tcin             wcin
#   define tclog            wclog
#   define tcout            wcout
 
#else // defined UNICODE || defined _UNICODE
 
    typedef string          tstring;
 
    typedef stringbuf       tstringbuf;
    typedef stringstream    tstringstream;
    typedef ostringstream   tostringstream;
    typedef istringstream   tistringstream;
 
    typedef streambuf       tstreambuf;
 
    typedef istream         tistream;
    typedef iostream        tiostream;
 
    typedef ostream         tostream;
 
    typedef filebuf         tfilebuf;
    typedef fstream         tfstream;
    typedef ifstream        tifstream;
    typedef ofstream        tofstream;
 
    typedef ios             tios;
 
#   define tcerr            cerr
#   define tcin             cin
#   define tclog            clog
#   define tcout            cout
 
#endif // defined UNICODE || defined _UNICODE
} // namespace std
© . All rights reserved.