checking expression validity in-place with C++17--Vittorio Romeo

An introduction to the world of C++17.

checking expression validity in-place with C++17

by Vittorio Romeo

From the article:

When writing generic code, it is sometimes useful to check whether or not a particular SFINAE-friendly expression is valid (e.g. to branch at compile-time). Let's assume that we have the following class declarations...

struct Cat
{
    void meow() const { cout << "meow\n"; }
};

struct Dog
{
    void bark() const { cout << "bark\n"; }
};

...and that we would like to write a template function make_noise(x) that calls x.meow() and/or  x.bark() if they are well-formed expressions:

template <typename T>
void make_noise(const T& x)
{
    // Pseudocode:
    /*
        if(`x.meow()` is well-formed)
        {
            execute `x.meow();`
        }
        else if(`x.bark()` is well-formed)
        {
            execute `x.bark();`
        }
        else
        {
            compile-time error
        }
    */
}

In this article I'll show how to implement the pseudocode in:

C++11: using std::void_t and std::enable_if.

C++14: using boost::hana::is_valid and vrm::core::static_if.

C++17: using if constexpr(...), constexpr lambdas, and std::is_callable. This version will allow expression validity to be checked in-place (i.e. directly in the if constexpr predicate). Variadic preprocessor macros will also be used to make the user code easier to read and maintain...

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.