Deriving the template argument type from the class definition

Is it possible to use the output of a class template argument for a class Cfrom the definition of one of the member functions C? ... or am I forced to write my helper class make_c, as in C ++ 03?

Consider this minimized and simplified scenario that creates a chain of arbitrary functional objects:

template <typename F>
struct node;

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

The class nodestores a function object that is initialized with a perfect transfer. I need a guide for extracting here to decayfunction type object.

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 , node ( , ). .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; });
                    ^

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)};
}

wandbox

..., .

, make_node?

+4
2

node , . ( .)

, , .

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>;
+6

, make.

: make_node - T, .

template <template <typename...> class T, typename... Ts>
auto make(Ts&&... xs)
    noexcept(noexcept(T{std::forward<Ts>(xs)...}))
    -> decltype(T{std::forward<Ts>(xs)...})
{
    return T{std::forward<Ts>(xs)...};
}

:

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

Source: https://habr.com/ru/post/1681107/


All Articles