c++ - 类模板的 C++1 7's "模板参数推导可以推导局部类型吗?

标签 c++ templates gcc c++17 template-argument-deduction

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/

相关文章:

c++ - 在类模板(链接列表)中重载运算符

c++ - 如何使用可变模板参数为元组专门化类模板?

C++如何将源代码生成的映射包含到预编译阶段的应用程序中

wpf - 使用视觉状态管理器设置前景时出现问题

c++ - 无法启动 UE4Editor.exe

c - gcc2.9到5.3不同的汇编指令

c++ - self 背后的理论和用法是什么,包括 C 和 C++ 中的源文件?

c - 没有完整路径的 gcc : error trying to exec 'cc1' : execvp: No such file or directory

java - C/C++/Java问题: will the expression used in for loop evaluate multiple times?

c++ - 将类的对象返回到主程序