vendredi 24 septembre 2021

Casting to void to Avoid Use of Overloaded User Defined Comma Operator

I am learning about templates in C++ and came across an example where casting to void is used(shown below).

template<typename T>
auto func (T const& t) -> decltype( (void)(t.size()), T::size_type() )
{
return t.size();

}

In the explanation it is written that

The cast of the expression to void is to avoid the possibility of a user-defined comma operator overloaded for the type of the expressions.

My question(s) is/are:

  1. How can a cast to void be used to avoid the possibility of a user-defined comma operator overloaded for the type of the expressions. I mean can anyone give any example where if we don't use void then this code would give error. For example lets say we have a class called SomeClass which has overloaded the comma operator. Now can this become a problem if we don't use void.
  2. Can static_cast be used in this case instead of C style cast. For example something like static_cast<void>(t.size()) . I am reading examples that use C++17 features and so i wonder why the author has used C style cast in this case.

I have read this from which i get the impression that if we use (void)x; then this means to suppress compiler warnings and also means "ignore the value of x". But then i can't understand the difference between the expression x; and (void)x;.

Aucun commentaire:

Enregistrer un commentaire