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

给定以下代码(从此处获取):

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

上面的代码在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)...);
}

对于上面的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.

如果我尝试“选项2”。我得到几乎相同的错误。

除了看起来很冗长之外,我似乎也无法做到这一点。谁能提供一些我做错了什么的见解?有没有更简单的方法来提供返回类型?

博格丹

您的第一个选择的错误消息是由于以下事实

std::declval<func_type>()(std::forward<Ts>(ts)...)

您尝试f1使用两个类型double参数(传递给的参数)来调用仿函数operator(),但是它需要一个std::pairfunc_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;
}

笔记:

  • 它可以在C ++ 11模式下的GCC 4.9.1和Clang 3.5.0上以及Visual C ++ 2013上编译和运行。
  • 如所写,ret_hlp仅处理声明operator()与lambda闭包类型相似的函数对象类型,但可以轻松地将其扩展到几乎所有其他类型,包括普通函数类型。
  • 我试图尽可能少地更改原始代码。我认为该代码需要提到一个重要的方面:如果compose给定了左值参数(如本例所示),则functionTuple内部compose_impl将存储对这些参数的引用这意味着只要使用了复合函子,原始函子就需要一直可用,否则您将有悬挂的引用。

编辑:这是根据注释的要求提供的关于最后一个音符的更多信息:

该行为归因于转发引用的工作方式-的Fs&& ...功能参数compose如果您具有某种形式的函数参数,正在F&&为其执行模板参数推导(如此处所示),并且A为该参数提供了类型的参数,则:

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

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

compose_impl<lambda_1_type&, lambda_2_type&, lambda_3_type&>

反过来会使functionTuple类型

std::tuple<lambda_1_type&, lambda_2_type&, lambda_3_type&>

如果您将lambda表达式作为参数直接传递给compose,则根据上述内容,functionTuple其类型为

std::tuple<lambda_1_type, lambda_2_type, lambda_3_type>

因此,只有在后一种情况下,元组才会存储功能对象的副本,从而使组成的功能对象类型自成一体。

现在,这不是好事还是坏事的问题。而是您想要什么的问题。

如果您希望组成的对象始终是独立的(存储函子的副本),则需要摆脱这些引用。一种实现方法是使用std::decay,因为它不仅可以删除引用,还可以处理函数到指针的转换,如果您希望扩展compose_impl以能够处理普通函数,这将很方便

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

std::tuple<typename std::decay<Fs>::type ...> functionTuple;

结果是将始终在元组内复制或移动功能对象,因此即使在原始组件被销毁后,也可以使用生成的组合功能对象。

哇好久 也许您不应该说“精心” :-)。


编辑2,来自OP的第二条评论:是的,不带代码std::decayret_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';
}

的行为c3可能不是您想要的或期望的。更不用说所有这些变体可能会使您的代码确定混乱ret_type

随着std::decay到位,所有的三个变种存储指针功能f

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章