mardi 18 décembre 2018

How to force member functions of class templates to be instantiated?

I have recently found out that the member functions of class templates aren't instantiated until they're used, which is extremely annoying because it makes certain SFINAE constructs not work. I would like to know how to make sure that a member function of a class template specialization is always instantiated as soon as the class is instantiated -- but only using statements inside the class template definition, so that if the member function could not be instantiated, SFINAE kicks in and the compiler falls back on the general class template.

The code I was planning to use looks like this:

template <typename T, typename U>
class test_type {
    // general template; dummy parameter U is to allow specialization.
    static const bool value = false;
}

template <typename T>
class test_type<T, T> {
    // template specialization
    void f(T t) {
        // do all sorts of type-specific operations with t
        // (e.g., calling member functions)

        // if T is not suitable for these operations, I want
        // a substitution error to be generated so that the
        // general template is used instead
    }

    static const bool value = true;
}

template <typename T>
using satisfies = test_type<T, T>::value;

Aucun commentaire:

Enregistrer un commentaire