Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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_

like image 372
Violet Giraffe Avatar asked Jan 02 '23 16:01

Violet Giraffe


2 Answers

One option is to remove the static_assert and instead mark the function as deleted. Then if you call it with an rvalue you will get an error saying you are trying to use a deleted function

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

}

template <size_t N>
void f(const std::array<char, N>&& arr) = delete; // used const here just in case we get a const prvalue

int main()
{
    std::array<char, 3> foo{};
    f(foo);
    //f(std::array<char, 3>{}); // error
    return 0;
}
like image 188
NathanOliver Avatar answered Jan 18 '23 23:01

NathanOliver


Simple enough.

template <size_t N>
void f(const std::array<char, N>&& arr) = delete;
like image 31
SergeyA Avatar answered Jan 18 '23 22:01

SergeyA