CString ToString() 模板重载 for CppUnitTestFramework.

CString ToString() template overload for CppUnitTestFramework

本文关键字:重载 for CppUnitTestFramework ToString CString      更新时间:2023-10-16

如何为 CStrings编写C++ VS2012 CppUnitTestFramework ToString() 模板重载?这必须是可能的。

编译器说我必须,因为它给出了编译错误:

error C2338: Test writer must define specialization of ToString<const Q& q> for your class class std::basic_string<unsigned short,struct std::char_traits<unsigned short>,class std::allocator<unsigned short> > __cdecl Microsoft::VisualStudio::CppUnitTestFramework::ToString<class ATL::CStringT<unsigned short,class StrTraitMFC<unsigned short,class ATL::ChTraitsCRT<unsigned short> > >>(const class ATL::CStringT<unsigned short,class StrTraitMFC<unsigned short,class ATL::ChTraitsCRT<unsigned short> > > &).

对于其他数据类型,我在单元测试代码中添加了与此类似的内容:

using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework {
template<> static std::wstring ToString<eNumy>(const eNumy & e) {   return ltots(static_cast<long>(e)); }

我尝试添加:

template<> static std::wstring ToString<CString>(const CString & e) { return e.GetBuffer(); }

但这无法与 const 问题一起编译:

error C2663: 'ATL::CSimpleStringT<BaseType>::GetBuffer' : 2 overloads have no legal conversion for 'this' pointer

有人有什么想法吗?

我想运行这个测试:

CString csTina;
CString csGeoff;
Assert::AreNotEqual(csTina, csGeoff);

是的,你有它:CString的函数GetBuffer未标记为const函数,因此您无法在const CString&上调用此函数。

多种选择:

  • 从重载中删除const
  • 在没有GetBuffer的情况下实现逻辑。
  • 执行const_cast以获取它。(虽然推荐)。
  • 只需将CString转换为std::string(或std::wstring)并使用现有功能即可。