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_
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;
}
Simple enough.
template <size_t N>
void f(const std::array<char, N>&& arr) = delete;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With