确定是否正在传递一个临时的
Determining if being passed a temporary
假设我有一个类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
}
相关文章:
- 此代码是否违反一个定义规则
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- 是否可以同时声明一个类成员的常量/非常量?
- C++-字符串是否包含一个带有简单循环的单词
- 检查注册表项是否链接到(或副本)另一个注册表项
- 在C++行尾写一个分号或多个分号是否会改变任何内容
- 一元*运算符的操作数是否期望一个 prvalue
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- 是否可以使用一个类来控制 C++ 中另一个类的对象?(阿杜伊诺)
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 检查 2D 网格的某个元素是否与另一个元素共享对角线、水平线或垂直线
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 是否可以创建一个从不同类调用函数的线程?
- 这些场景中的任何一个是否会造成内存泄漏
- 在一个结构中,使用一个数组字段访问另一个是否合法
- C++检查前 5 个或接下来的 5 个元素中的任何一个是否等于值