我喜欢尽可能多地使用
auto
,但有一种情况到目前为止我还没有解决方案。
场景是我必须在范围之外声明变量,但在范围内初始化它,通常是
try/catch
。这是一个经典的例子:
std::vector<std::shared_ptr<Some::Custom::Type> Initialize()
{
return {};
}
void Use()
{
// delctype(Initialize) result; // not working
// auto result; // completely different
std::vector<std::shared_ptr<Some::Custom::Type> result // so much typing
try
{
result = Initialize();
}
catch(...) {}
....
}
PS。我知道您可以通过在
try
范围内执行其余代码来避免此问题,但有时您需要这样。
有没有办法在 C++20 之前实现 delctype(Initialize) result;
习惯用法?
您可以使用
delctype(Initialize())
:
struct long_name {};
long_name initialize() { return {}; }
int main()
{
decltype(initialize()) value;
{
value = initialize();
}
}
(演示)
std::invoke_result
。