mardi 29 décembre 2020

Forcing instantiation of all of a template classes member functions

During initial development of a template class, before I've written full test cases, I am finding that I would like the ability to force the compiler to generate the code for every member (including non-static ones) of a template class for a specific set of template parameters, just to make sure all the code at least compiles.

Specifically, I'm using GCC 9 (I don't really need this ability for other compilers, since it's just something I want to temporarily make happen during development); and its c++14, c++17, c++2a and c++20 standards.

For example, I might write the following code:

template <typename D> struct test_me {
  D value;
  void mistake1 () { value[0] = 0; }
  void mistake2 () { mistake1(value); }
  // and a bajillion other member functions...
};

And, given that I know in advance the finite set of possible template parameters (let's say int and float here), I just want to make sure they at least compile while I'm working.

Now I can do this, which obviously falls short:

int main () {
  test_me<int> i;
  test_me<float> f;
}

Since mistake1 and mistake2 aren't generated, the code compiles fine despite the indexed access attempt to a non-array type, and the incorrect function call.

So what I've been doing during development is just writing code that calls all the member functions:

template <typename D> static void testCalls () {
    test_me<D> t;
    t.mistake1();
    t.mistake2();
    // and so on... so many mistakes...
}

int main () {
   testCalls<int>();
   testCalls<float>();
}

But this gets to be a pain, especially when the member functions start to have complex side effects or preconditions, or require nontrivial parameters, or have non-public members and not-yet-developed friends. So, I'd like a way to test compilation without having to explicitly call everything (and, ideally, I'd like to be able to test compilation without modifying any "test" code at all as I add new members).

So my question is: With at least GCC 9, is there a way to force (potentially temporarily) the compiler to generate code for a template class's entire set of members, given template parameters?

Aucun commentaire:

Enregistrer un commentaire