在Visual Studio 2005上使用TCHAR进行C++模板函数特化

Eli*_*Eli 0 c++ templates wchar-t widestring template-specialization

我正在编写一个使用模板化运算符<< function的日志类.我专门研究宽字符串的模板函数,这样我就可以在写日志消息之前做一些从宽到窄的翻译.我不能让TCHAR正常工作 - 它不使用专业化.想法?

这是相关的代码:

// Log.h header
class Log
{
  public:
    template <typename T> Log& operator<<( const T& x );

    template <typename T> Log& operator<<( const T* x );

    template <typename T> Log& operator<<( const T*& x );

    ... 
}

template <typename T> Log& Log::operator<<( const T& input )
{ printf("ref"); }

template <typename T> Log& Log::operator<<( const T* input )
{ printf("ptr"); }

template <> Log& Log::operator<<( const std::wstring& input );
template <> Log& Log::operator<<( const wchar_t* input );
Run Code Online (Sandbox Code Playgroud)

和源文件

// Log.cpp 
template <> Log& Log::operator<<( const std::wstring& input )
{ printf("wstring ref"); }
template <> Log& Log::operator<<( const wchar_t* input )
{ printf("wchar_t ptr"); }
template <> Log& Log::operator<<( const TCHAR*& input )
{ printf("tchar ptr ref"); }
Run Code Online (Sandbox Code Playgroud)

现在,我使用以下测试程序来练习这些功能

// main.cpp - test program
int main()
{
 Log log;
 log << "test 1";
 log << L"test 2";
 std::string test3( "test3" );
 log << test3;
 std::wstring test4( L"test4" );
 log << test4;
 TCHAR* test5 = L"test5";
 log << test5;
}
Run Code Online (Sandbox Code Playgroud)

运行上述测试显示以下内容:

// Test results
ptr
wchar_t ptr
ref
wstring ref
ref
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不太对.我真的很喜欢最后一个是"TCHAR",所以我可以转换它.根据Visual Studio的调试器,当我进入在测试5中调用的函数时,类型是wchar_t*& - 但它没有调用适当的特化.想法?

我不确定它是否相关,但这是在Windows CE 5.0设备上.

jwi*_*mar 5

TCHAR是一个宏,它为wchar_t或char引用了typedef.当您实例化模板时,宏已被替换.您将最终引用char的模板实例或wchar_t的模板实例.