如何推断以引用为参数的函数的返回类型
How to deduce the return type of a function which takes a reference as parameter
我正在尝试推断函数的返回类型并将其用作成员函数的返回类型。为此,我使用了一个 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();
}
我想
你正在寻找std::declval<data_type&>()
第一个失败是因为类在函数声明中不完整,因为它在成员函数体中不完整,因此只能使用已声明的成员。
对于第二种,标准库提供 declval
,一个声明为返回其模板参数类型的函数模板。当您需要特定类型的表达式时,可以在未计算的上下文中使用它。
所以以下版本应该有效:
#include <utility> // for declval
template<typename data_type, typename functor_type>
class MyClass
{
private:
// Declare this before `func1`
data_type m_data;
public:
// Use the already declared member variable
auto func1() -> decltype(functor_type::process(m_data))
{
return functor_type::process(m_data);
}
// Or use `declval` to get an expression with the required reference type
auto func2() -> decltype(functor_type::process(std::declval<data_type&>()))
{
return functor_type::process(m_data);
}
};
相关文章:
- 检查函数返回类型是否与STL容器类型值相同
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 在 c++ 中将函数返回类型指定为模板参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 如何避免模板函数返回类型重复?
- 从类型bankAccount的返回值到函数返回类型int没有可行的转换
- 为什么在某些情况下从函数返回类型中删除 cv 限定符?
- 模板类内模板类的函数返回类型
- 为什么函数返回类型中不允许参数推导?
- 函数返回类型之前的"define"
- C++推断要隐式调用的模板函数返回类型
- 具有不同模板参数的函数返回类型
- 当函数返回类型为父类时,如何返回子类的对象?
- C++:在原型中声明"auto"函数返回类型仍然会导致在扣除错误之前使用"auto&quo
- C++14 'auto'能够获取函数返回类型,我们还需要 std::result_of<> 吗?
- 函数返回类型中的模板类型推断
- 嵌套模板类返回类型在 C++ 中的头文件中函数返回类型的语法
- C++重写 void 函数返回类型会导致生成失败
- 从函数内部推断函数返回类型
- C++嵌套类函数返回类型和命名空间