简体   繁体   English

比较枚举类型

[英]Compare enum types

I am implementing some unit test using cpp unit test framework for visual studio.我正在使用 Visual Studio 的 cpp 单元测试框架实现一些单元测试。 I want to be able to compare enums in the test but there is always an error that keeps showing up.我希望能够在测试中比较枚举,但总是有一个错误不断出现。

This is the code that causes me the error.这是导致我出错的代码。

ClauseEntities ent1 = varMap.at("a");
ClauseEntities ent2 = varMap.at("v");

Assert::AreEqual(ent1, ASSIGN_STATEMENT);
Assert::AreEqual(ent1, VARIABLE);

ent1 is a enum state and ASSIGN_STATEMENT is also an enum state from the same enum. ent1 是一个枚举状态,而 ASSIGN_STATEMENT 也是来自同一个枚举的一个枚举状态。

Severity    Code    Description Project File    Line    Suppression State
Error   C2338   Test writer must define specialization of ToString<const Q& q> 
for your class class std::basic_string<wchar_t,struct 
std::char_traits<wchar_t>,class std::allocator<wchar_t> > __cdecl 
Microsoft::VisualStudio::CppUnitTestFramework::ToString<enum ClauseEntities>
(const enum ClauseEntities &).  
UnitTesting C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\VS\UnitTest\include\CppUnitTestAssert.h 66  

Not sure how i am supposed to create a template specialisation for to string of enums..不知道我应该如何为枚举字符串创建模板专业化..

I have never used microsoft cpp unit tests, but from the error message and experience with gtests I think you have to add a method ToString for your enum class.我从未使用过 microsoft cpp 单元测试,但从错误消息和 gtests 的经验来看,我认为您必须为枚举类添加一个方法ToString (My guess is) It is because if the Assert fails, both arguments are printed to some output using ToString method. (我的猜测是)这是因为如果 Assert 失败,两个参数都会使用ToString方法打印到某些输出。

At the end of this article similar problem is solved.在结束这个文章类似的问题就解决了。

This is quite simple这很简单

namespace Microsoft {
namespace VisualStudio {
namespace CppUnitTestFramework { // not sure if namespaces are actually needed

std::wstring ToString(ClauseEntities value)
{
    switch (value) {
    case ClauseEntities::ValueA: return L"ValueA"; //assuming that you are using enum class
    case ClauseEntities::ValueB: return L"ValueB";
    }

    return std::to_wstring(static_cast<int>(value));
}

} // namespace CppUnitTestFramework 
} // namespace VisualStudio
} // namespace Microsoft

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM