boostorg / boostorg/hof

Macro facilitating perfectly forwarded `this` pointers

Open
#157 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
509
Forks
94
PR merge metrics
No merged PRs in 30d

Description

I thought of a potential Fit feature today when browsing [this r/cpp thread](https://www.reddit.com/r/cpp/comments/4b7zfe/a_possible_c_standard_proposal_on_overloading/).

It would be nice sometimes to write the same function for all function qualifier overloads, especially for generic programming. The following macro, `FIT_OVERLOAD_ALL_QUALIFIERS`, facilitates this. The first argument to this macro is the user-facing member name, and the second argument is the static internal implementation, which takes a universal reference representing `*this`.

``` cpp
#include

#define FIT_OVERLOAD_ALL_DETAIL(name, impl, qual) \
template \
decltype(auto) name(Args&&... args) qual { \
using this_t = std::remove_reference_t< \
decltype(*this) \
>; \
return impl( \
static_cast(*this), \
static_cast(args)... \
); \
} \
/**/

#define FIT_OVERLOAD_ALL_QUALIFIERS(name, impl) \
FIT_OVERLOAD_ALL_DETAIL(name, impl, &) \
FIT_OVERLOAD_ALL_DETAIL(name, impl, &&) \
FIT_OVERLOAD_ALL_DETAIL(name, impl, const &) \
FIT_OVERLOAD_ALL_DETAIL(name, impl, const &&) \
FIT_OVERLOAD_ALL_DETAIL(name, impl, volatile &) \
FIT_OVERLOAD_ALL_DETAIL(name, impl, volatile &&) \
FIT_OVERLOAD_ALL_DETAIL(name, impl, const volatile &) \
FIT_OVERLOAD_ALL_DETAIL(name, impl, const volatile &&) \
/**/

//

#include

struct foo {

FIT_OVERLOAD_ALL_QUALIFIERS(operator(), print_qualifiers)

template
static void print_qualifiers(ThisRef&&) {
using no_ref = std::remove_reference_t;

if (std::is_const{}) {
std::cout << "const ";
}

if (std::is_volatile{}) {
std::cout << "volatile ";
}

if (std::is_rvalue_reference{}) {
std::cout << "&& ";
}
else if (std::is_lvalue_reference{}) {
std::cout << "& ";
}

std::cout << '\n';
}
};

int main() {
using F = foo;
using CF = const foo;
using VF = volatile foo;
using VCF = const volatile foo;

F f{};
CF cf{};
VF vf{};
VCF vcf{};

f();
cf();
vf();
vcf();

F{}();
CF{}();
VF{}();
VCF{}();
}
```

Output:

```
&
const &
volatile &
const volatile &
&&
const &&
volatile &&
const volatile &&
```

I'd be happy to submit a PR with test cases and tweaks if there is further interest here.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.