Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Write one function for all combinations of const and volatile

12 views
Skip to first unread message

Frederick Virchanza Gotham

unread,
Sep 18, 2022, 4:35:56 PM9/18/22
to

Recently I wanted to have a class with a method called "Drop" that would return 'this', and so I wrote the following:

class MyClass {

#define DROP(modifiers) \
MyClass modifiers *Drop(void) modifiers \
{ \
return this; \
}

DROP()
DROP(const)
DROP(volatile)
DROP(const volatile)

};

Is there a better way of writing a member function just once and then having it work for all combinations of 'const' and 'volatile'?

Alf P. Steinbach

unread,
Sep 18, 2022, 4:59:59 PM9/18/22
to
Off the cuff:

// C++ support machinery.

template< class Derived, Base >
constexpr bool is_same_or_derived_and_base_ =
std::is_base_of_v<Base, Derived>; // (sic!)

template< bool condition >
using Enable_if_ = std::enable_if_v<condition, int>;

template< class T > using const_ = const T;

// Problem solution: use a freestanding function.
// Possibly with trivial non-static member function wrappers.

struct My_class {};

template<
class T,
Enable_if_<is_same_or_derived_and_base_<T, My_class>> = 0
>
auto drop( const_<T*> p ) -> T* { return p; }

Disclaimer: not checked by a compiler.

See also: upcoming C++23 support for exactly this problem; <url:
https://www.google.com/search?q=c%2B%2B23+deduced+this>.

- Alf


Alf P. Steinbach

unread,
Sep 18, 2022, 5:00:59 PM9/18/22
to
oh should be enable_if_t, not v. gah.

- Alf


0 new messages