decltype为递归类型的递归可变参数函数模板

cel*_*vek 4 c++ decltype variadic-templates c++11 c++14

给出以下代码(取自此处):

#include <cstddef>
#include <type_traits>
#include <tuple>
#include <iostream>
#include <utility>
#include <functional>

template<typename ... Fs>
struct compose_impl
{
    compose_impl(Fs&& ... fs) : functionTuple(std::forward_as_tuple(fs ...)) {}

    template<size_t N, typename ... Ts>
    auto apply(std::integral_constant<size_t, N>, Ts&& ... ts) const
    {
        return apply(std::integral_constant<size_t, N - 1>(), std::get<N>  (functionTuple)(std::forward<Ts>(ts)...));
    }

    template<typename ... Ts>
    auto apply(std::integral_constant<size_t, 0>, Ts&& ... ts) const
    {
        return std::get<0>(functionTuple)(std::forward<Ts>(ts)...);
    }

    template<typename ... Ts>
    auto operator()(Ts&& ... ts) const
    {
         return apply(std::integral_constant<size_t, sizeof ... (Fs) - 1>(), std::forward<Ts>(ts)...);
    }

    std::tuple<Fs ...> functionTuple;
};

template<typename ... Fs>
auto compose(Fs&& ... fs)
{
     return compose_impl<Fs ...>(std::forward<Fs>(fs) ...);
}

int main ()
{
    auto f1 = [](std::pair<double,double> p) {return p.first + p.second;    };
    auto f2 = [](double x) {return std::make_pair(x, x + 1.0); };
    auto f3 = [](double x, double y) {return x*y; };
    auto g = compose(f1, f2, f3);

    std::cout << g(2.0, 3.0) << std::endl;   //prints '13', evaluated as (2*3) + ((2*3)+1)
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码适用于C++ 14.我在使它适用于C++ 11时遇到了一些麻烦.我试图为所涉及的功能模板正确提供返回类型,但没有太大的成功,例如:

template<typename... Fs>
struct compose_impl
{
    compose_impl(Fs&&... fs) : func_tup(std::forward_as_tuple(fs...)) {}

    template<size_t N, typename... Ts>
    auto apply(std::integral_constant<size_t, N>, Ts&&... ts) const -> decltype(std::declval<typename std::tuple_element<N, std::tuple<Fs...>>::type>()(std::forward<Ts>(ts)...))
    // -- option 2. decltype(apply(std::integral_constant<size_t, N - 1>(), std::declval<typename std::tuple_element<N, std::tuple<Fs...>>::type>()(std::forward<Ts>(ts)...)))
    {
         return apply(std::integral_constant<size_t, N - 1>(), std::get<N>(func_tup)(std::forward<Ts>(ts)...));
    }

    using func_type = typename std::tuple_element<0, std::tuple<Fs...>>::type;
    template<typename... Ts>
    auto apply(std::integral_constant<size_t, 0>, Ts&&... ts) const -> decltype(std::declval<func_type>()(std::forward<Ts>(ts)...))
    {
        return std::get<0>(func_tup)(std::forward<Ts>(ts)...);
    }

    template<typename... Ts>
    auto operator()(Ts&&... ts) const -> decltype(std::declval<func_type>()(std::forward<Ts>(ts)...))
    // -- option 2. decltype(apply(std::integral_constant<size_t, sizeof...(Fs) - 1>(), std::forward<Ts>(ts)...))
    {
        return apply(std::integral_constant<size_t, sizeof...(Fs) - 1>(), std::forward<Ts>(ts)...);
    }

    std::tuple<Fs...> func_tup;
};

template<typename... Fs>
auto compose(Fs&&... fs) -> decltype(compose_impl<Fs...>(std::forward<Fs>(fs)...))
{
   return compose_impl<Fs...>(std::forward<Fs>(fs)...);
}
Run Code Online (Sandbox Code Playgroud)

对于上面的clang(3.5.0)给出了以下错误:

func_compose.cpp:79:18: error: no matching function for call to object of type 'compose_impl<(lambda at func_compose.cpp:65:15) &, (lambda at func_compose.cpp:67:15) &,
  (lambda at func_compose.cpp:68:15) &>'
std::cout << g(2.0, 3.0) << std::endl;   //prints '13', evaluated as (2*3) + ((2*3)+1)
             ^
 func_compose.cpp:31:10: note: candidate template ignored: substitution failure [with Ts = <double, double>]: no matching function for call to object of type
  '(lambda at func_compose.cpp:65:15)'
 auto operator()(Ts&&... ts) /*const*/ -> decltype(std::declval<func_type>()(std::forward<Ts>(ts)...))
     ^                                            ~~~
1 error generated.
Run Code Online (Sandbox Code Playgroud)

如果我尝试"选项2".我得到了几乎相同的错误.

除了它看起来非常冗长之外,我似乎也无法做到正确.谁能提供一些有关我做错的见解?有没有更简单的方法来提供返回类型?

bog*_*dan 6

第一个选项的错误消息是由于in的事实

std::declval<func_type>()(std::forward<Ts>(ts)...)
Run Code Online (Sandbox Code Playgroud)

你试图f1用两个类型的参数double(传递给operator()它)来调用仿函数,但它需要一个std::pair(func_type指的是元组中第一个仿函数的类型).

关于选项2,它不编译的原因是尾部返回类型是函数声明符的一部分,并且在看到声明decltype(apply(...))符的结尾之前不会将该函数视为声明,因此您不能在尾随返回中使用第一个声明的类型apply.


我相信你现在很高兴知道为什么你的代码不能编译,但我想如果你有一个可行的解决方案,你会更高兴.

我认为有一个重要的事实需要首先澄清:applyoperator()模板的所有特化compose_impl 都有相同的返回类型 - f1在这种情况下,第一个仿函数的返回类型.

有几种方法可以获得该类型,但快速入侵如下:

#include <cstddef>
#include <type_traits>
#include <tuple>
#include <iostream>
#include <utility>
#include <functional>

template<typename> struct ret_hlp;

template<typename F, typename R, typename... Args> struct ret_hlp<R (F::*)(Args...) const>
{
    using type = R;
};

template<typename F, typename R, typename... Args> struct ret_hlp<R (F::*)(Args...)>
{
    using type = R;
};

template<typename ... Fs>
struct compose_impl
{
    compose_impl(Fs&& ... fs) : functionTuple(std::forward_as_tuple(fs ...)) {}

    using f1_type = typename std::remove_reference<typename std::tuple_element<0, std::tuple<Fs...>>::type>::type;
    using ret_type = typename ret_hlp<decltype(&f1_type::operator())>::type;

    template<size_t N, typename ... Ts>
    ret_type apply(std::integral_constant<size_t, N>, Ts&& ... ts) const
    {
        return apply(std::integral_constant<size_t, N - 1>(), std::get<N>  (functionTuple)(std::forward<Ts>(ts)...));
    }

    template<typename ... Ts>
    ret_type apply(std::integral_constant<size_t, 0>, Ts&& ... ts) const
    {
        return std::get<0>(functionTuple)(std::forward<Ts>(ts)...);
    }

    template<typename ... Ts>
    ret_type operator()(Ts&& ... ts) const
    {
         return apply(std::integral_constant<size_t, sizeof ... (Fs) - 1>(), std::forward<Ts>(ts)...);
    }

    std::tuple<Fs ...> functionTuple;
};

template<typename ... Fs>
compose_impl<Fs ...> compose(Fs&& ... fs)
{
     return compose_impl<Fs ...>(std::forward<Fs>(fs) ...);
}

int main ()
{
    auto f1 = [](std::pair<double,double> p) {return p.first + p.second;    };
    auto f2 = [](double x) {return std::make_pair(x, x + 1.0); };
    auto f3 = [](double x, double y) {return x*y; };
    auto g = compose(f1, f2, f3);

    std::cout << g(2.0, 3.0) << std::endl;   //prints '13', evaluated as (2*3) + ((2*3)+1)
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 它在C++ 11模式和Visual C++ 2013上编译和使用GCC 4.9.1和Clang 3.5.0.
  • 如上所述,ret_hlp只处理声明operator()类似于lambda闭包类型的函数对象类型,但它可以很容易地扩展到其他任何东西,包括普通函数类型.
  • 我试图尽可能少地改变原始代码; 我认为关于该代码需要提到一个重要的部分:如果compose给出了左值参数(如本例所示),functionTupleinside compose_impl将存储对这些参数的引用.这意味着只要使用复合仿​​函数,原始仿函数就必须可用,否则你将有悬空参考.

编辑:以下是评论中要求的最后一个注释的更多信息:

这种行为是由于转发引用的工作方式 - Fs&& ...函数参数compose.如果你有一个函数参数,F&&正在进行模板参数推导(就像这里一样),并A为该参数给出了一个类型的参数,那么:

  • 如果参数表达式是一个rvalue,F则推导为A,并且当替换回函数参数时,它会给出A&&(例如,如果你直接将lambda表达式作为参数传递给它)会发生这种情况compose;
  • 如果参数表达式是左值,F则推导为A&,并且,当替换回函数参数时,它给出A& &&,A&根据参考折叠规则得出(这是在当前示例中发生的,因为f1其他是左值) .

因此,在当前示例中,compose_impl将使用推导出的模板参数进行实例化(如使用发明的名称用于lambda闭包类型)

compose_impl<lambda_1_type&, lambda_2_type&, lambda_3_type&>
Run Code Online (Sandbox Code Playgroud)

这反过来会使functionTuple类型

std::tuple<lambda_1_type&, lambda_2_type&, lambda_3_type&>
Run Code Online (Sandbox Code Playgroud)

如果你将lambda表达式直接作为参数传递给compose,那么,根据上面的说法,functionTuple将具有该类型

std::tuple<lambda_1_type, lambda_2_type, lambda_3_type>
Run Code Online (Sandbox Code Playgroud)

因此,只有在后一种情况下,元组才会存储函数对象的副本,从而使组合的函数对象类型成为自包含的.

现在,这不是一个好或坏的问题; 这是你想要的问题.

如果您希望组合对象始终是自包含的(存储仿函数的副本),那么您需要摆脱这些引用.这里做的一种方法是使用std::decay,因为它不仅仅删除引用 - 它还处理函数到指针的转换,如果你想扩展compose_impl以便能够处理普通函数,它会派上用场.

最简单的方法是更改​​声明functionTuple,因为它是您关注当前实现中引用的唯一位置:

std::tuple<typename std::decay<Fs>::type ...> functionTuple;
Run Code Online (Sandbox Code Playgroud)

结果是,函数对象将始终在元组内复制或移动,因此即使在原始组件被破坏后,也可以使用生成的组合函数对象.

哇,这很久了; 也许你不应该说'精心':-).


编辑2来自OP的第二条评论:是的,代码实际上没有std::decay(但扩展为正确确定ret_type普通函数参数,如你所说)将处理普通函数,但要小心:

int f(int) { return 7; }

int main()
{
    auto c1 = compose(&f, &f); //Stores pointers to function f.
    auto c2 = compose(f, f); //Stores references to function f.
    auto pf = f; //pf has type int(*)(int), but is an lvalue, as opposed to &f, which is an rvalue.
    auto c3 = compose(pf, pf); //Stores references to pointer pf.
    std::cout << std::is_same<decltype(c1.functionTuple), std::tuple<int(*)(int), int(*)(int)>>::value << '\n';
    std::cout << std::is_same<decltype(c2.functionTuple), std::tuple<int(&)(int), int(&)(int)>>::value << '\n';
    std::cout << std::is_same<decltype(c3.functionTuple), std::tuple<int(*&)(int), int(*&)(int)>>::value << '\n';
}
Run Code Online (Sandbox Code Playgroud)

行为c3可能不是你想要的或人们期望的.更不用说所有这些变体都可能会混淆您的代码以进行确定ret_type.

有了这个std::decay,所有三个变体都存储指向功能的指针f.