【发布时间】:2013-05-30 02:32:59
【问题描述】:
首先我构造了四个结构体,每个结构体返回值、左值引用、常量左值引用、右值引用。我在包装器中使用它们(B 或 C),在这些包装器的方法 func() 中,
我想保留 func() 的引用和 cv 限定符 A。
在 c++11 中,我使用了尾随返回类型。但是随着c++14中正常返回类型推导的到来,我猜我可以跳过尾部,但只有auto,返回类型会像普通的auto一样忽略限定符和引用。
然后,我的问题是在 c++14 中实现它的最佳方法是什么,它的行为就像下面的 B 类?
在琐碎的时候写尾部(通常是decltype(返回表达式))有时会令人沮丧。
struct A1 {
int func(){
return x;
}
int x{3};
};
struct A2 {
int& func(){
return x;
}
int x{3};
};
struct A3 {
const int& func(){
return x;
}
int x{3};
};
struct A4 {
int&& func(){
return std::move(x);
}
int x{3};
};
template <class A>
struct B{
auto func() -> decltype(std::declval<A>().func())
{
return a.func();
}
A a;
};
template <class A>
struct C{
auto func()
{
return a.func();
}
A a;
};
int main(){
std::cout << std::boolalpha;
B<A1> b1;
B<A2> b2;
B<A3> b3;
B<A4> b4;
static_assert(std::is_same<decltype(b1.func()), int>::value, "true");
static_assert(std::is_same<decltype(b2.func()), int&>::value, "true");
static_assert(std::is_same<decltype(b3.func()), const int&>::value, "true");
static_assert(std::is_same<decltype(b4.func()), int&&>::value, "true");
C<A1> c1;
C<A2> c2;
C<A3> c3;
C<A4> c4;
static_assert(std::is_same<decltype(c1.func()), int>::value, "true");
static_assert(std::is_same<decltype(c2.func()), int>::value, "true");
static_assert(std::is_same<decltype(c3.func()), int>::value, "true");
static_assert(std::is_same<decltype(c4.func()), int>::value, "true");
}
请注意,这个程序在 gcc 4.8 中使用 -std=c++1y 选项编译没有问题。
【问题讨论】:
-
@rhalbersma:感谢您提供的信息。