Search code examples
c++c++-conceptsc++23

why concept requirement not take effect


In following code, it compileds under -std=c++23 flag. Why the concept requirement, that the In parameter should not be reference triggered?

#include <concepts>
#include <type_traits>
#include <functional>

template <typename T>
concept NotRef = requires { !std::is_reference_v<T>; };

template <typename In, typename Out>
    requires NotRef<In> // requires that In should not be reference
class SwitchType
{
    using ConstIn = std::add_const_t<In>;
public:
    SwitchType(const In& in)
        : in_{in}
    { }
    ConstIn & in_;
};

int main()
{
    int a{9};
    // Expected behavior: 'requirement not satifsfied'
    // Actural behavior: compiles under c++ 23

    SwitchType<int&, int> mytype{a};
}

Solution

  • What you have is a simple requirement. This is simply checking if !std::is_reference_v<T> is a valid expression (which it will be).

    You want to check the boolean value of that expression, which is done like this:

    template <typename T>
    concept NotRef = !std::is_reference_v<T>;