jeudi 25 octobre 2018

Overload a method in a way that generates a compiler error when called with a temporary

Perhaps this piece of code will illustrate my intent best:

#include <array>

template <size_t N>
void f(std::array<char, N> arr)
{
}

template <size_t N>
void f(std::array<char, N>&& arr)
{
    static_assert(false, "This function may not be called with a temporary.");
}

f() should compile for lvalues but not for rvalues. This code works with MSVC, but GCC trips on the static_assert even though I'm pretty sure this overload is never called.

So my question is two-fold: how to express my intent properly with modern C++, and why does the compiler evaluate static_assert in a "dead" template overload that's never instantiated?

Try it online: https://godbolt.org/z/yJJn7_

Aucun commentaire:

Enregistrer un commentaire