Search code examples
c++templatesdefaultenable-ifconditional-types

template class default type and condition


I want to use std::enable_if for MyClass in order to accept only (uint32_t | uint64_t) and at the same time if the user did not provide any type; a default one is picked according to bellow condition.

but I can't get it to work. (C++17)

#include <vector>
#include <cstdint>

template <typename T=std::conditional_t<sizeof(void*) == 8, std::uint64_t, std::uint32_t>>
class MyClass
{
  private:
    std::vector<T> vs;
  public:
  // ...
};


int main(){
  MyClass a; // OK, the defaut type is used either uint32_t or uint64_t
  MyClass<std::uint32_t> b; // Ok, use the user provided type
  MyClass<long> c; // must not compile, T is not one of uint32_t, uint64_t
}

Solution

  • You can add static_assert to perform the checking.

    template <typename T=std::conditional_t<sizeof(void*) == 8, std::uint64_t, std::uint32_t>>
    class MyClass
    {
      static_assert(std::is_same_v<T, std::uint64_t> || std::is_same_v<T, std::uint32_t>, "T must be std::uint64_t or std::uint32_t");
      private:
        std::vector<T> vs;
      public:
      // ...
    };
    

    LIVE