Search code examples
c++c++20c++-conceptsrequires-expression

Implicit copyable requirement of requires expression


Does the following code requires an implicit copy constructor for T, because the parameters are passed by value? Or does it behave like decltype and there's no real construction involved?

template<typename T>
concept Addable = requires (T a, T b){ a + b; };

Solution

  • That concept simply checks that a + b is a valid expression. The a and b there are simply invented objects that are lvalues of type T - they are not at all constructed.

    If the expression a + b, based on how operator+ is defined, results in copying, then that copy will also be checked as part of seeing if the expression is valid. But otherwise, no.

    For instance:

    struct A {
        A(A const&) = delete;
        A& operator=(A const&) = delete;
        void operator+(A const&) const;
    };
    
    // A is noncopyable, but Addable
    static_assert(Addable<A>);
    
    struct B {
        B(B const&) = delete;
        B& operator=(A const&) = delete;
        friend void operator+(B, B) { }
    };
    
    // B is noncopyable, but not Addable
    // (because invoking + requires copying)
    static_assert(!Addable<B>);