Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用google test打印std::chrono类型?_C++_Googletest - Fatal编程技术网

C++ 如何使用google test打印std::chrono类型?

C++ 如何使用google test打印std::chrono类型?,c++,googletest,C++,Googletest,我试图在google测试中使用std::chrono类型。我的第一种方法是在名称空间std::chrono中定义PrintTo的nanoseconds,但不幸的是。下面的代码演示了这个想法 #include <gtest/gtest.h> #include <chrono> namespace std::chrono { void PrintTo(nanoseconds ns, std::ostream* os) // UB { *os << ns

我试图在google测试中使用
std::chrono
类型。我的第一种方法是在名称空间
std::chrono
中定义
PrintTo
nanoseconds
,但不幸的是。下面的代码演示了这个想法

#include <gtest/gtest.h>
#include <chrono>

namespace std::chrono {

void PrintTo(nanoseconds ns, std::ostream* os) // UB
{
    *os << ns.count() << " nanoseconds ";
}

}

namespace {

struct MyTest : ::testing::Test{
};

TEST_F(MyTest, PrintingTest)
{
    using namespace testing;
    using namespace std::chrono_literals;
    ASSERT_THAT(1ns, Eq(2ns));
}

}
如果未定义
std::chrono::PrintTo
,则通过默认字节打印机打印:

Value of: 1ns
Expected: is equal to 8-byte object <02-00 00-00 00-00 00-00>
  Actual: 
的值:1ns
应为:等于8字节对象
实际:

使用google test为
std::chrono
类型定义打印机的惯用方法是什么?

您可以为chrono类型重载std::ostream操作符,如下所示:

#include <gtest/gtest.h>
#include <chrono>

std::ostream& operator<<(std::ostream& os, const ::std::chrono::nanoseconds& ns) 
{
  return os << ns.count() << " nanoseconds ";
}

namespace {

struct MyTest : ::testing::Test{
};

TEST_F(MyTest, PrintingTest)
{
    using namespace testing;
    using namespace std::chrono_literals;
    ASSERT_EQ(1ns, 2ns);
}

}

顺便说一句,如果有另一个cpp文件没有定义
operator@DevNull是的,但是你的选择是“未定义的行为”和“可能的ODR”,我不知道是否还有其他合适的方法。我在测试中使用了UB(如您的问题中所述)实现,我认为在这种情况下,它是可以接受的,并且为当前STL正确定义,它可能在将来成为UB。也许gtest github页面上的一个问题应该是尝试询问开发人员他们的建议UB的问题是它可以工作,但它可能不。。。我有两个目标,一个是gcc(7.5),一个是clang(8.0.1)。此解决方案适用于第一个解决方案,但不适用于后一个解决方案。@您可能需要将实现移动到std::chrono命名空间中,就像原始问题对PrintTo()所做的那样。如果这两种方法都适用,那么最好知道给定解决方案中哪一种是正确的,哪一种是错误的。但是扩展std名称空间本身不是UB吗?这将解决问题。
#include <gtest/gtest.h>
#include <chrono>

std::ostream& operator<<(std::ostream& os, const ::std::chrono::nanoseconds& ns) 
{
  return os << ns.count() << " nanoseconds ";
}

namespace {

struct MyTest : ::testing::Test{
};

TEST_F(MyTest, PrintingTest)
{
    using namespace testing;
    using namespace std::chrono_literals;
    ASSERT_EQ(1ns, 2ns);
}

}
error:       Expected: 1ns
      Which is: 1 nanoseconds
To be equal to: 2ns
      Which is: 2 nanoseconds
[  FAILED  ] MyTest.PrintingTest (0 ms)