Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of empty structs in C++

Tags:

c++

struct

In some code that I was reading, I found the usage of empty struct like so:

struct input_iterator_tag { };
struct bidirectional_iterator_tag { };
struct random_access_iterator_tag { };

So in the rest of the code, it was used as what they call tag dispatching.

I was wondering if there is other usage of empty structs.

from an older post I saw that :

three major reasons we use empty structs in C++ are:

  • a base interface
  • a template parameter
  • a type to help overload resolution. (tag dispatching if I am not wrong)

Could someone explain that please?

like image 942
Blood-HaZaRd Avatar asked Nov 15 '25 22:11

Blood-HaZaRd


1 Answers

a type to help overload resolution. (tag dispatching if I am not wrong)

When you want to use a complex template specialization pattern on some function, you don't try to go at it directly, but rather write:

template <typename T1, typename T2, other things maybe>
int foo(T1 param1, T2 param2 and so on)
{
    using tag = put your complex stuff here, which produces an empty struct
    detail::foo_impl(tag, std::forward<T1>(param1), std::forward<T2>(param2) and so on);
}

Now, the compiler doesn't have to decide between competing choices of template specialization, since with different tags you get incompatible functions.

a base interface

struct vehicle { 
    // common members and methods,
    // including (pure) virtual ones, e.g.
    virtual std::size_t num_maximum_occupants() = 0;
    virtual ~vehicle() = default;
};

namespace mixins {
struct named { std::string name; };
struct wheeled { int num_wheels; public: rev() { }; };

}  // namespace mixins
    
struct private_sedan : public vehicle, public wheeled, named {
   // I dunno, put some car stuff here
   //
   // and also an override of `num_maximum_occupants()`
};

Making the base struct completely empty is perhaps not that common, but it's certainly possible if you use mixins a lot. And you could check for inheritance from vehicle (although I'm not sure I'd do that).

a template parameter

Not sure what this means, but venturing a guess:

template <typename T>
struct foo { };

template <typename T, typename N>
struct foo<std::array<T, N>> {
    int value = 1;
};

If you now use foo<T>::value in a function, it will work only if T is int with few (?) exceptions.

like image 130
einpoklum Avatar answered Nov 18 '25 12:11

einpoklum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!