【问题标题】:C++: Deriving a function return type using decltypeC++:使用 decltype 派生函数返回类型
【发布时间】:2015-06-12 02:07:22
【问题描述】:

以下是真实 C++14 应用程序的(过度)简化摘录。出于可维护性的原因,我不想明确指定 foo() 的返回类型。我知道 C++14 可以推断出函数的返回类型automatically。但真正的应用程序需要函数内部的返回类型。所以我需要它。

下面的代码sn-p编译好(g++ 4.9.2):

#include <type_traits>
#include <iostream>
#include <string>

//auto foo (std::wstring &s) -> std::remove_reference <decltype (s)>::size_type
auto foo (std::wstring &s) -> decltype (s.length ())
    {
    return s.length ();
    }

int main ()
    {
    std::wstring s {L"hello world"};
    std::cout << foo (s) << "\n";
    return 0;
    }

但如果我使用函数声明的“注释掉”版本,我会得到以下诊断结果:

foo.cpp:5:69: error: ‘size_type’ in ‘struct std::remove_reference<std::basic_string<wchar_t>&>’ does not name a type
auto foo (std::wstring &s) -> std::remove_reference <decltype (s)>::size_type
                                                                    ^

怎么了? std::wstring::size_type 不是一个类型吗? std::remove_reference 不是将std::basic_string&lt;wchar_t&gt;&amp; 转换为普通的std::wstring 吗?

【问题讨论】:

    标签: c++11 c++14 return-type decltype


    【解决方案1】:

    std::remove_reference 没有size_type 成员,std::wstring 有。您可以使用std::remove_reference&lt;decltype(s)&gt;::type 访问std::wstring。因此,您真正需要的返回类型是:

    std::remove_reference <decltype (s)>::type::size_type
    

    由于您使用的是 C++14,因此您可以改用 std::remove_reference_t,这是为便于阅读而引入的别名模板快捷方式:

    std::remove_reference_t <decltype (s)>::size_type
    

    编辑:正如@Cassio 在 cmets 中所指出的,由于您使用的是 C++14,您也可以让函数使用 auto 推断返回类型,这将自动剥离参考:

    auto foo (std::wstring &s)
        {
        return s.length ();
        }
    

    也就是说,你真的应该考虑when you really want to do it。许多人更喜欢在有意义的情况下使用显式返回类型。

    【讨论】:

    • 建议改进你的答案:既然是C++14,我们可以使用函数返回类型推导,直接写auto foo (std::wstring&amp; s) { return s.length (); }
    • 正如我在最初的帖子中已经说过的那样,这个例子过于简单化了。事实上(再次如前所述)我需要 inside 函数的类型。因此 C++14 的返回类型推导在这里没有帮助。
    猜你喜欢
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    相关资源
    最近更新 更多