以临时方式调用时以产生编译器错误的方式重载方法 [英] 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()
应该为左值而不是右值编译。这段代码适用于MSVC,但是即使从未调用此重载,GCC也会在 static_assert
上跳闸。
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.
问题有两个:如何用现代C ++正确表达我的意图,为什么编译器会在从未实例化的死模板重载中评估 static_assert
?
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?
在线试用: https://godbolt.org/z/ yJJn7_
推荐答案
一种选择是删除 static_assert
而是将该功能标记为已删除。然后,如果您使用右值调用它,则会收到一条错误消息,提示您正在尝试使用已删除的函数
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;
}
这篇关于以临时方式调用时以产生编译器错误的方式重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!