簡體   English   中英

如何推導以引用為參數的函數的返回類型

[英]How to deduce the return type of a function which takes a reference as parameter

我試圖推論一個函數的返回類型,並將其用作成員函數的返回類型。 為此,我使用了decltype表達式。 但是,如果給定函數將引用作為參數,則所有嘗試都無法編譯:

  • 我不能在decltype表達式中使用類的任何成員變量,因為編譯器會抱怨沒有這樣的成員(請參見下面的func1
  • 我不能對函數參數使用臨時變量,因為該函數需要一個引用,並且您不能將非常量左值引用綁定到臨時func2 (請參見下面的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);
    }
};    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM