【发布时间】:2014-02-26 11:44:21
【问题描述】:
我正在尝试推断函数的返回类型并将其用作成员函数的返回类型。为此,我使用了 decltype 表达式。但是如果给定的函数将引用作为参数,我所有的尝试都无法编译:
- 我不能在 decltype 表达式中使用我的类的任何成员变量,因为编译器抱怨没有这样的成员(参见下面的
func1) - 我不能为函数参数使用临时值,因为函数需要一个引用,并且您不能将非常量左值引用绑定到临时值(参见下面的
func2)
我还尝试了各种强制转换运算符来使引用成为临时的,但似乎没有什么是有效的表达式。
这里是一个代码示例:
template<typename data_type, typename functor_type>
class MyClass
{
public:
auto func1() -> decltype(functor_type::process(this->m_data)) // <--
{
return functor_type::process(m_data);
}
auto func2() -> decltype(functor_type::process(data_type{})) // <--
{
return functor_type::process(m_data);
}
private:
data_type m_data;
};
struct Functor
{
static int process(int& a) { return a; }
};
int main()
{
MyClass<int, Functor> m;
int b = m.func1();
int c = m.func2();
}
【问题讨论】:
-
为了让
func1工作,将m_data的声明移到它前面。 Example
标签: c++ c++11 pass-by-reference decltype return-type-deduction