Edward Diener
Edward Diener

Reputation: 147

C++ class template with non-type parameter depending on type parameter problem using C++11

I understand that the normal means in C++ of controlling at compile time which class template member functions are included/excluded is through partial specialization. I have a class template which has a type parameter and a non-type parameter depending on the type parameter. When the non-type parameter is a certain value I want certain member functions of a class template to be part of the instantiation of the class template but not others. The normal way of doing this is to code the primary template to include certain member functions and then to code a partial specialization of the primary template with a different set of member functions. But because of the rule which says:

"Non-type template argument cannot specialize a template parameter whose type depends on a parameter of the specialization" I can not do this. Is there a way around this ? Simple example code would look like:

  template 
    <
    class T, 
    T * v
    >
  struct  AClassTemple
    {
    void SomeMemberFunction() { code etc. }
    void AnotherMemberFunction() { code etc. }
    };

When 'v' is a nullptr I want my class template to not include AnotherMemberFunction and its code, which assumes a value for 'v' which is not a nullptr. I can not partially specialize the class template by specifying:

  template 
    <
    class T 
    >
  struct  AClassTemple<T,nullptr>
     {
     };

etc. else I get a compiler error reflecting the rule above.

Upvotes: 0

Views: 94

Answers (1)

n314159
n314159

Reputation: 5075

The following should do what you want:

#include <type_traits>

template<class T, T *v>
struct AClassTemple {
    template<T *w = v, class = std::enable_if_t<w != nullptr>>
    void SomeMemberFunction() {}

    template<T *w = v, class = std::enable_if_t<w != nullptr>>
    void AnotherMemberFunction() {}
};

int main() {
    constexpr static char c = '0';
    AClassTemple<int, nullptr> a{};
    AClassTemple<const char, &c> b{};

    // a.SomeMemberFunction(); // will not compile
    b.SomeMemberFunction();
}

Upvotes: 2

Related Questions