我正在使用 CPPUnit 来测试程序中的一个类。这个类 (SCriterionVal
) 有点独特,因为它具有许多类型的转换运算符(它本质上是一个动态类型值类)。当我编译使用 CPPUNIT_ASSERT_EQUAL()
进行测试的测试用例时,我从 CPPUnit 头文件之一收到有关“operator<<
is ambigeous”的编译错误。看起来它正在使用我的类型实例化 assertion_traits
结构,并且该结构有一个 toString()
方法,该方法通过使用 operator<<
来工作> 在 OStringStream
上。
我认为它是不明确的而不是错误,因为 SCriterionVal 上可用的各种转换,其中一些已经定义了运算符<<(例如内置类型)。为了纠正这种情况,我在 SCriterionVal
的标头中创建了一个具有以下签名的非成员函数:
ostream &operator<<(ostream &stream, SCriterionVal val);
我认为因为签名应该完全匹配,所以它将解决歧义。没有这样的运气。我在这里做错了什么?我想我可以为我的类型专门化 assertion_traits
的模板,但我希望能够解决更普遍的问题,即提供一种将我的类放入流中的方法,而不仅仅是迎合测试框架。
I am using CPPUnit to test a class in my program. This class (SCriterionVal
) is somewhat unique because it has conversion operators for a lot of types (it's essentially a dynamic type value class). When I compile test cases that test it using CPPUNIT_ASSERT_EQUAL()
, I get compilation errors about "operator<<
is ambiguous" from one of the CPPUnit header files. It appears that it is instantiating the assertion_traits
struct with my type, and that struct has a toString()
method that works by using operator<<
on an OStringStream
.
I assume it's ambiguous instead of an error because of the various conversions available on SCriterionVal
, some of which have defined operator<<
(such as the built in types). In an attempt to rectify this situation, I created a non-member function in the header for SCriterionVal
with this signature:
ostream &operator<<(ostream &stream, SCriterionVal val);
I figured because the signature should be an exact match, it will resolve the ambiguity. No such luck. What am I doing wrong here? I suppose I can specialize the template for assertion_traits
for my type, but I was hoping to be able to solve the more general problem of providing a way to put my class into a stream, rather than just catering to the test framework.
发布评论
评论(1)
尝试将
operator<<
定义为类定义中的友元内联函数。我总是发现这种方式效果最好,尤其是对于模板。例如,Boost.Random 在
指数分布
的声明中定义了operator<<
:Try defining
operator<<
as a friend inline function inside the class definition. I always find this way works the best, especially for templates.For example, Boost.Random defines
operator<<
insideexponential distribution
's declaration: