确定是否正在传递一个临时的

Determining if being passed a temporary

本文关键字:一个 是否      更新时间:2023-10-16

假设我有一个类C和一个函数make_c(x),它创建c的实例。

C参考x存储

我怎么能写make_c(x)给出一个编译错误时,x是一个未命名的临时(这当然会破坏在行结束,留下一个悬空的引用),但接受命名的临时和其他值?

我相信这应该有你正在寻找的语义:

template<typename X>
C make_c(X&& x)
{
    static_assert(
        !std::is_rvalue_reference<decltype(std::forward<X>(x))>::value,
        "x must not be a temporary"
    );
    return C(std::forward<X>(x));
}

注意:由于在vc++ 2010中decltype的实现存在缺陷(您需要将decltype包装在std::identity<>中),因此不能按原来的方式工作。

我认为这在语言中是不可能的,因为你需要通过任意函数检查流控制。

struct Foo{
};
Foo const & sanitize(Foo const & f){ return f;}
void checkThisFunction(Foo const & f){
   //we'd like to ensure at compile time that f is not a temporary
}
int main(){
   Foo f;
   checkThisFunction(sanitize(f));
   checkThisFunction(sanitize(Foo()));
   return 0;
}

除非我完全误解了右值引用,否则这种事情应该可以通过简单的重载来实现。

void foo(int&&) = delete;
void foo(const int&) { }
int main()
{
   int a;
   foo(a);
   foo(42);  //error, prefers binding to the deleted overload
}
相关文章: