Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to std::variant<unsigned long, size_t, unsigned int>

Tags:

c++

enable-if

I ran into a portability issue, which is due to the fact that size_t varies between platforms (sometimes it is equiv to unsigned int, sometimes to unsigned long)

What I would like to write is:


"if constexpr" / "enable_if" / "whatever"  (size_t == unsigned long)
  using V = std::variant<unsigned int, size_t>;
else
  using V = std::variant<unsigned long, size_t>;

What is the less ugly way to write it?

Links to compiler explorer snippet:

https://godbolt.org/z/AZVFEz : using gcc 9.2 64 bits where size_t <-> unsigned long

https://godbolt.org/z/wWeCbW : using msvc 19.22 32 bits where size_t <-> unsigned int

like image 795
Pascal T. Avatar asked Dec 03 '25 18:12

Pascal T.


1 Answers

Since you want a conditional type alias, you may use std::conditional

using V = std::conditional_t<std::is_same_v<std::size_t, unsigned long>,
            std::variant<unsigned int, size_t>,
            std::variant<unsigned long, size_t>
          >;
like image 57
StoryTeller - Unslander Monica Avatar answered Dec 06 '25 08:12

StoryTeller - Unslander Monica