C++ needs undefined behavior, but maybe less

The C++ standard does not specify all behavior. Some things are up to the implementation, while other operations are completely undefined, and the compiler is free to do whatever it wants. This is essential for some optimizations but can also be dangerous. The newly proposed erroneous behavior addresses it, but it cannot be used to eliminate all undefined behavior.

» read at think-cell »
Jonathan

Compile-time sizes for range adaptors

In my previous blog post, we’ve discussed the static constexpr std::integral_constant idiom to specify the size of a range at compile-time. Unlike the standard, our [think-cell’s] ranges library at think-cell already supports compile-time sizes natively, so I was eager to try the idiom there and see how it works out in practice.

namespace tc
{
    template <typename Rng>
    constexpr auto size(Rng&& rng); // runtime-size of a range, like std::ranges::size

    template <typename Rng> requires tc::has_constexpr_size<Rng>
    constexpr auto constexpr_size = ; // compile-time size of a range given its type
}
» read at think-cell »
Jonathan

The new static constexpr std::integral_constant idiom

The size of std::array<T, N> is known at compile-time given the type. Yet it only provides a regular .size() member function:

template <typename T, std::size_t N>
struct array {
    constexpr std::size_t size() const {
        return N;
    }
};

This is annoying if you’re writing generic code that expects some sort of compile-time sized range.

» read at think-cell »
Jonathan

Constrain your user-defined conversions

Sometimes you want to add an implicit conversion to a type. This can be done by adding an implicit conversion operator. For example, std::string is implicitly convertible to std::string_view:

class string { // template omitted for simplicity
public:
    operator std::string_view() const noexcept
    {
       return std::string_view(c_str(), size());
    }
};

The conversion is safe, cheap, and std::string and std::string_view represent the same platonic value — we match Tony van Eerd’s criteria for implicit conversions and using implicit conversions is justified.

However, even when all criteria are fulfilled, the conversion can still be dangerous.

» read at think-cell »
Jonathan