【发布时间】: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<wchar_t>& 转换为普通的std::wstring 吗?
【问题讨论】:
标签: c++11 c++14 return-type decltype