§3.10第9节说"非类别rvalues总是有cv不合格类型".这让我很奇怪......
int foo()
{
return 5;
}
const int bar()
{
return 5;
}
void pass_int(int&& i)
{
std::cout << "rvalue\n";
}
void pass_int(const int&& i)
{
std::cout << "const rvalue\n";
}
int main()
{
pass_int(foo()); // prints "rvalue"
pass_int(bar()); // prints "const rvalue"
}
Run Code Online (Sandbox Code Playgroud)
根据标准,对于非类型类型没有const rvalue,但bar()更喜欢绑定const int&&.这是编译器错误吗?
编辑:显然,this也是一个const rvalue :)
编辑:这个问题似乎在g ++ 4.5.0中得到修复,现在两行打印"rvalue".
哪个更好:
bool MyClass::someQuery() const;
const bool MyClass::someQuery() const;
Run Code Online (Sandbox Code Playgroud)
我一直在使用'const bool',因为我确信我记得听到它是"什么样做的"(例如比较运营商)但我无法在任何地方找到证据,主要是因为它很难谷歌和Intellisense没有帮助任何人;)任何人都可以确认吗?
对我来说,返回const值(这不仅仅是关于bools)更有意义; 它会阻止临时修改,这几乎总是一个程序员的错误.我只是想要一些东西来支持这一点,所以我可以赞美给我的同事们返回const值:)
我创建了一个简单的类型特征来删除右值引用:
template <typename T>
struct remove_rvalue_reference { using type = T; };
template <typename T>
struct remove_rvalue_reference<T&&> { using type = T; };
template <typename T>
using remove_rvalue_reference_t =
typename remove_rvalue_reference<T>::type;
Run Code Online (Sandbox Code Playgroud)
我用它来实现一个copy_if_rvalue(x)函数,其返回类型取决于传递的参数:
template <typename T>
constexpr auto copy_if_rvalue(T && x)
-> remove_rvalue_reference_t<decltype(std::forward<decltype(x)>(x))>
{
return std::forward<decltype(x)>(x);
}
Run Code Online (Sandbox Code Playgroud)
为了确保函数返回正确的类型,我编写了一些简单的静态断言:
// literal
static_assert(std::is_same<
decltype(copy_if_rvalue(0)), int
>{});
// lvalue
int lv = 10;
static_assert(std::is_same<
decltype(copy_if_rvalue(lv)), int&
>{});
// const lvalue
const int clv = 10;
static_assert(std::is_same<
decltype(copy_if_rvalue(clv)), const int& …Run Code Online (Sandbox Code Playgroud)