如何使模板推导出具有可变参数的函数返回类型

时间:2017-09-25 09:21:40

标签: c++ templates generics variadic

堆栈溢出的人写了一个有趣的方法来将lambda或functor捕获到你自己的类中。我试图简化它,我认为我很接近,但遇到了一些麻烦。他们的例子是:

// OT => Object Type
// RT => Return Type
// A ... => Arguments

template<typename OT, typename RT, typename ... A>
struct lambda_expression {
    OT _object;
    RT(OT::*_function)(A...)const; // A pointer to a member function, 
                                   // specifically the operator()

    lambda_expression(const OT & object) // Constructor
        : _object(object), 
          _function(&decltype(_object)::operator()) {} // Assigning the function pointer

    RT operator() (A ... args) const {
        return (_object.*_function)(args...);
    }
};

基本上这可以让你去:

int captureMe = 2;
auto lambda = [=](int a, int b) { return a + b + captureMe;};
lambda_expression<decltype(lambda), int, int, int>(lambda); 

我试图简化这一点,并认为lambda_expression类中包含的指针不是必需的,因为你可以调用函数对象本身,而不是调用指向operator()的指针。所以我尝试了这个:

template <typename OT, typename ... Args>   // No Return type specified
struct lambdaContainer
{
    lambdaContainer(OT funcObj) : funcObj(funcObj){ }
    OT funcObj; // No pointer, just the function object.

    auto operator()(Args... args) 
    {
        return funcObj(args...); // Call the function object directly
    }
};

然后像:

int captureMe = 2;
auto lambda = [=](int a, int b) { return a + b + captureMe; };

lambdaContainer<decltype(lambda), int, int> lam(lambda);

auto i = lam(1, 1);
// i = 4;

我写的那条线:

auto operator()(Args... args) 
    {
        return funcObj(args...); 
    }

显然:

 decltype(auto) operator()(Args... args) //works in C++14 apparently.

但是我试过没有auto关键字而且我在这样做时失败了,我想了解Args是如何工作的。我试过了:

decltype(funObj(Args...) operator()(Args... args) // this failed
decltype(OT(Args...) operator() (Args... args) // this failed
auto operator() (Args... args) -> decltype(funcObj(Args...)) // this failed
auto operator() (Args... args) -> decltype(OT(Args...)) // this failed

如何扩展Args参数,以便模板可以推断出返回类型?这只适用于自动吗?

1 个答案:

答案 0 :(得分:1)

decltype(e)使用表达式 e并计算该表达式的类型。您需要提供一个表示存储的lambda调用的表达式

auto operator()(Args... args) 
    -> decltype(std::declval<OT>()(std::declval<Args>()...))

在这种情况下,我正在使用std::declval来创建可用于演绎目的的对象的“假实例”,而不实际调用任何构造函数。

让我们进一步分解:

-> decltype(
    std::declval<OT>()          // create a fake instance of `OT`
    (                           // invoke it
        std::declval<Args>()... // create a fake instance of each argument 
                                // type, expanding `Args...`
    )
)

live example on wandbox

顺便说一句,您仍应std::forward调用funcObj中的参数,因为可能有一些右值引用需要进一步向下传播:

auto operator()(Args... args) 
{
    return funcObj(std::forward<Args>(args)...); 
}
相关问题