开发者

How to write test for C++ templates?

开发者 https://www.devze.com 2023-02-08 11:14 出处:网络
Suppose I am writing a template library consisting of a function template template<T> void f(T);

Suppose I am writing a template library consisting of a function template

template<T> void f(T);

with the requirement that it works with a predefined set of classes A, B, C, and D, e.g., the following must compile:

template<> void f(A);
template<> void f(B);
template<> void f(C);
template<> void f(D);

Which test framework can I use to write test cases that captures this requirement at runtime instead of failing at compilation of the test code? In another word, I would like the framework to instantiate the templates at runtime and produce a nicely formatted error report if a subset of them fails.

I know I can forego test frameworks altogether and simply write a simple cc file containing the 4 lines above. But I was hoping I could incorporate this requirement into regular, standard test cases for generation of test status reports. For example,

test f works with A: passed.
test f works with B: passed.
test f works with C: failed!  Cannot cast type C!
test f works with D: pas开发者_StackOverflow社区sed.

3 of 4 tests passed.
1 of 4 tests failed.


Write a test case that spawns the compiler... that's how e.g. autoconf tests for existence of features.


I don't understand why failing at runtime is preferable to failing at compile time. The earlier you fail in the unit testing process the better. It is preferable to have your unit tests not compile than fail. Its even easier to fix, In fact it probably won't even be committed to source control. Your unit test should just include those four lines and assert true at the end. Note this isn't the way I would go about doing it myself.


C++ templates are a compile time feature. In many cases they will fail at compile time, by design. You simply can't get around this without doing something really crazy.

However, you're also going to want to know that your template specializations are correct, because the specializations override the behavior you would otherwise get from the template. So test the specializations. But realize you will never get around the compile time aspects of templates.


Based on what you're trying to test here, checking if the thing can compile is the only sensible test you can perform.

Testing should not be for the sake of testing, but to ensure functional correctness. If you want to have proper tests around your class, you should write tests that verify the functionality of your template with all of the 4 different classes it can be compiled with.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号