gpt4 book ai didi

c++ - 从类定义中推导模板参数类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:34:27 25 4
gpt4 key购买 nike

是否可以使用 class template argument deduction上课 C来自 C 之一的定义内的成员函数? ...还是我被迫写我的 make_c类似于 C++03 中的辅助类?

考虑这个构建任意函数对象链的最小化和简化场景:

template <typename F>
struct node;

template <typename FFwd>
node(FFwd&&) -> node<std::decay_t<FFwd>>;

node类存储一个通过完美转发初始化的函数对象。我需要一个演绎指南这里decay函数的类型 对象。

template <typename F>
struct node
{
F _f;

template <typename FFwd>
node(FFwd&& f) : _f{std::forward<FFwd>(f)}
{
}

template <typename FThen>
auto then(FThen&& f_then)
{
return node{[f_then = std::move(f_then)]
{
return f_then();
}};
}
};

然后,我定义node的构造函数和一个 .then返回一个新节点的延续成员函数(它的实现对于最小化示例的大小是无意义的)。如果我尝试调用 .then ...

auto f = node{[]{ return 0; }}.then([]{ return 0; });

...我收到意外的编译错误:

prog.cc: In instantiation of 'node<F>::node(FFwd&&) [with FFwd = node<F>::then(FThen&&) [with FThen = main()::<lambda()>; F = main()::<lambda()>]::<lambda()>; F = main()::<lambda()>]':
prog.cc:27:22: required from 'auto node<F>::then(FThen&&) [with FThen = main()::<lambda()>; F = main()::<lambda()>]'
prog.cc:35:56: required from here
prog.cc:17:46: error: no matching function for call to 'main()::<lambda()>::__lambda1(<brace-enclosed initializer list>)'
node(FFwd&& f) : _f{std::forward<FFwd>(f)}
^
prog.cc:35:20: note: candidate: 'constexpr main()::<lambda()>::<lambda>(const main()::<lambda()>&)'
auto f = node{[]{ return 0; }}.then([]{ return 0; });
^

live example on wandbox

发生这种情况是因为在 node<F>::then 的正文中, node{...}创建一个类型为 *this 的实例- 它不会触发参数类型推导。因此我不得不写:

template <typename FThen>
auto then(FThen&& f_then)
{
auto l = [f_then = std::move(f_then)]{ return f_then(); };
return node<std::decay_t<decltype(l)>>{std::move(l)};
}

live example on wandbox

...这违背了演绎指南的全部目的。

有没有一种方法可以在不引入代码重复或 make_node 的情况下使用类模板参数推导?功能?

最佳答案

node 的名称查找找到了注入(inject)的类名,未从中执行推导。 (在这种情况下执行推导会破坏向后兼容性。)

如果要推导,请限定名称以便找到命名空间成员。

template <typename FThen>
auto then(FThen&& f_then)
{
return ::node{[f_then = std::move(f_then)]
// ^^
{
return f_then();
}};
}

此外,编写指南的一种更简洁的方法是

template <typename F>
node(F) -> node<F>;

关于c++ - 从类定义中推导模板参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45010637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com