P0091R3 ("Template argument deduction for class templates")最近添加到 gcc
trunk并且可以在 wandbox 上进行测试.
我的想法是使用它来实现一个 “作用域守卫”只需几行代码:
scope_guard _([]{ cout << "hi!\n" });
我试过了 implementing it on wandbox ...
template <typename TF>
struct scope_guard : TF
{
scope_guard(TF f) : TF{f} { }
~scope_guard() { (*this)(); }
};
int main()
{
scope_guard _{[]{}};
}
...但是编译失败并出现以下错误:
prog.cc:6:5: error: 'scope_guard(TF)-> scope_guard<TF> [with TF = main()::<lambda()>]', declared using local type 'main()::<lambda()>', is used but never defined [-fpermissive]
scope_guard(TF f) : TF{std::move(f)} { }
^~~~~~~~~~~
然后我尝试了 using a non-lambda local type , 并得到同样的错误。
int main()
{
struct K { void operator()() {} };
scope_guard _{K{}};
}
之后,I tried a non-local type , 它按预期工作。
struct K { void operator()() {} };
int main()
{
scope_guard _{K{}};
}
此功能的设计方式是否可以防止推导本地类型?
或者这是 gcc
当前功能实现的缺陷吗?
最佳答案
这是当前实现中的一个错误:77890 (NEW 意味着有效性,而不是 UNCONFIRMED 在 7.0 中修复)。能够推导出 lambda 是原始论文的激励示例之一,所以如果它不起作用会很尴尬:
// Virtually impossible to pass a lambda to a template class' constructor without declaring the lambda for_each(vi2.begin(), vi2.end(), Foo<???>([&](int i) { ...}));
for_each(vi.begin(), vi.end(), Foo([&](int i) { ...})); // Now easy instead of virtually impossible
我们可以创建一个非常基本的示例:
template <typename TF>
struct scope_guard
{
scope_guard(TF ) { }
};
int main()
{
scope_guard _([]{});
}
这应该对由函数组成的合成函数集执行重载决议:
template <class TF> scope_guard<TF> synthesized(TF );
template <class TF> scope_guard<TF> synthesized(scope_guard<TF> const& );
template <class TF> scope_guard<TF> synthesized(scope_guard<TF>&& );
应该选择第一个重载并将该返回类型用作 _
的类型,其中 TF
是 lambda 的类型。这应该都有效。
关于c++ - 类模板的 C++1 7's "模板参数推导可以推导局部类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39916804/