簡體   English   中英

如何縮短此方法簽名?

[英]How to shorten this method signature?

我有以下帶有方法簽名的類,如下所示:

class Foo
{
    public:
        std::vector<std::string> barResults(const std::vector<std::string>&, const std::vector<std::string>&);
}

在實現文件中,我得到了以下信息:

std::vector<std::string> Foo::barResults(const std::vector<std::string>& list1, const std::vector<std::string>& list2)
{
    std::vector<std::string> results;
    // small amount of implementation here...
    return results;
}

所以我對自己想,讓我看看是否可以通過一些自動魔術來簡化此函數簽名,因為它已經變成了“滿滿的行”! 所以我嘗試了這個

class Foo
{
    public:
        auto barResults(const std::vector<std::string>&, const std::vector<std::string>&);
}

auto Foo::barResults(const std::vector<std::string>& list1, const std::vector<std::string>& list2)
{
    std::vector<std::string> results;
    // small amount of implementation here...
    return results;
}

現在忽略了一個事實,是的,我可以使用“ using namespace std”對其進行大量修整,我想知道為什么編譯器會給我一個錯誤“在定義前不能使用返回'auto'的函數”

我個人認為編譯器可以輕松推斷出該方法的返回類型,但在這種情況下似乎並非如此。 當然,您可以使用尾隨返回類型來修復它,如下所示:

class Foo
{
    public:
        std::vector<std::string> barResults(const std::vector<std::string>&, const std::vector<std::string>&) -> std::vector<std::string>;
}

但是,如果使用上面的方法,它不會比以前更好。 因此,除了“使用命名空間std”之外,還有一種更好的方法可以執行上述操作,為什么在這種情況下編譯器不能推斷出return類型? 甚至,這是否取決於此方法的調用方式,這將導致編譯器無法確定返回類型。

這里的問題是包含文件如何工作的問題。 您的錯誤:

返回'auto'的函數在定義之前不能使用

表示在文件中您正在使用函數,其定義(即實現)在使用前不在文件中的任何位置。 這意味着使用該函數編譯代碼的編譯器無法推斷出函數的返回類型,因為這需要訪問定義(實現)。 造成這種情況的最可能原因是該函數的定義(實現)位於其自己的源文件(.cpp,.c等)中,未包含在內。 為了更充分地理解這一點,我建議你閱讀這個答案,也許這個答案也。


為了解決名義上的問題,縮短簽名的最簡單方法可能是使用typedef。 更具體地說,您可以在合適的范圍內添加以下代碼(前提是范圍合適)(我將其添加為您班級的公共成員):

typedef std::vector<std::string> strvec;

這使您可以將方法簽名重新編寫為更易於管理:

strvec barreuslts(const strvec&, const strvec&)

堅持使用C ++ 11時,您不能依賴推導的返回類型,而需要尾隨的返回類型(盡管C ++ 14允許這樣做)。 由於在您的情況下,尾隨返回類型沒有什么特別的,即沒有通過decltype傳遞表達式來確定返回類型,因此,我將嘗試使用一些類型別名來縮短方法簽名:

class Foo
{
    public:
        using StrVec = std::vector<std::string>;

        StrVec barResults(const StrVec&, const StrVec&);
};

Foo::StrVec Foo::barResults(const StrVec& list1, const StrVec& list2)
{
    StrVec results;
    // small amount of implementation here...
    return results;
}

如果您只是在尋找一種視覺上吸引人的方式來處理更長的簽名,請不要將所有內容強制都放在一行上。 放寬您的垂直間距並插入換行符。 簽名包含呼叫者的質量信息,您可能需要的是多行簽名。 如果使用80個字符的頁面寬度,請重新考慮訪問說明符上的縮進。

class Foo
{
public:
    std::vector<std::string> barResults(const std::vector<std::string>&,
                                        const std::vector<std::string>&);
}


std::vector<std::string>
Foo::barResults(const std::vector<std::string>& list1,
                const std::vector<std::string>& list2)
{
    std::vector<std::string> results;
    // small amount of implementation here...
    return results;
}

拆分聲明有很多樣式。 在您的工具集中擁有像clang-format這樣的工具,將為您自動,一致地完成此操作。

暫無
暫無

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

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