【发布时间】:2017-11-23 10:06:26
【问题描述】:
在我的天真中,我认为这会编译。唉,不是。我正在使用完全更新的 Visual Studio 2017 社区。p>
namespace basic_problem {
auto msvc_does_not_compile = [] ( auto _string )
-> std::vector< decltype(_string) >
{
return std::vector<decltype(_string)>{};
};
}
编译尝试:
int main(int argc, char* argv[])
{
auto vec = basic_problem::msvc_does_not_compile(std::string{});
return 0 ;
}
生产:
error C2514: 'std::vector<unknown-type,std::allocator<_Ty>>': class has no constructors
1> with
1> [
1> _Ty=unknown-type
1> ]
1> program.cpp(97): note: see declaration of 'std::vector<unknown-
type,std::allocator<_Ty>>'
1> with
1> [
1> _Ty=unknown-type
1> ]
我知道我在这里达到了界限(也许)。有人知道吗?这在 C++17 中完全可行吗?基本上我想在运行时决定返回什么类型。不使用(明显的)模板。只是 'auto' 和 lambdas。
当然 C++ 不会让我这样做。但即使I use if constexprmsvc 拒绝打球:
auto msvc_does_not_compile_too = [](auto _string )
{
using string_type = decltype(_string);
if constexpr ( std::is_same<string_type, std::string>::value )
return std::vector<std::string> ;
else {
return std::vector<std::wstring>;
}
};
奇怪的是,我无法在编译时决定运行时需要什么类型。使用 lambda 和 auto,即。
谢谢...
【问题讨论】:
-
您的标题具有误导性。返回类型必须在编译时已知(当然可以是多态基类
std::any或std::variant)。在您的示例中,您使用的是模板化 lambda。关于您的问题:GCC 7.2.0 and Clang 5.0.0 compile your example without any issues. -
您是否包含
<vector>和<string>?包括我的 clang++ 和 g++ 编译你的第一个例子;没有<string>我会收到类似的错误。 -
@max66:godbolt.org link included in my first comment 显示与 MSVC 19 的问题类似的错误消息。
-
@Julius - 我明白了......好吧,我想是一个 VC++ 错误。
-
你真的需要尾随返回类型吗?
标签: c++ visual-c++ lambda c++17