kirakun
kirakun

Reputation: 2790

How to write test for C++ templates?

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: passed.

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

Upvotes: 6

Views: 2445

Answers (4)

Max Lybbert
Max Lybbert

Reputation: 20039

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.

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283634

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

Upvotes: 5

Steve
Steve

Reputation: 12004

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.

Upvotes: 2

Ateş G&#246;ral
Ateş G&#246;ral

Reputation: 140050

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.

Upvotes: 1

Related Questions