相关疑难解决方法(0)

是否有可能找出lambda的参数类型和返回类型?

给定一个lambda,是否可以找出它的参数类型和返回类型?如果有,怎么样?

基本上,我想要lambda_traits哪些可以用于以下方式:

auto lambda = [](int i) { return long(i*10); };

lambda_traits<decltype(lambda)>::param_type  i; //i should be int
lambda_traits<decltype(lambda)>::return_type l; //l should be long
Run Code Online (Sandbox Code Playgroud)

背后的动机是我想lambda_traits在一个接受lambda作为参数的函数模板中使用,我需要知道它的参数类型和函数内部的返回类型:

template<typename TLambda>
void f(TLambda lambda)
{
   typedef typename lambda_traits<TLambda>::param_type  P;
   typedef typename lambda_traits<TLambda>::return_type R;

   std::function<R(P)> fun = lambda; //I want to do this!
   //...
}
Run Code Online (Sandbox Code Playgroud)

目前,我们可以假设lambda只接受一个参数.

最初,我尝试使用std::function:

template<typename T>
A<T> f(std::function<bool(T)> fun)
{
   return A<T>(fun);
}

f([](int){return true;}); //error
Run Code Online (Sandbox Code Playgroud)

但它显然会给出错误.所以我将其更改TLambda为函数模板的版本,并希望在函数std::function内部构造对象(如上所示).

c++ lambda metaprogramming traits c++11

133
推荐指数
3
解决办法
3万
查看次数

std :: declval vs crtp,无法从不完整类型推断出方法返回类型

我正在尝试做这样的事情(在c ++ 11中):

#include <utility>

template <typename T>
struct base {
    using type = decltype( std::declval<T>().foo() );
};

struct bar : base<bar> {
    int foo() { return 42;}
};

int main() {
    bar::type x;
}
Run Code Online (Sandbox Code Playgroud)

失败与

prog.cc: In instantiation of 'struct base<bar>':
prog.cc:8:14:   required from here
prog.cc:5:46: error: invalid use of incomplete type 'struct bar'
     using type = decltype( std::declval<T>().foo() );
                            ~~~~~~~~~~~~~~~~~~^~~
prog.cc:8:8: note: forward declaration of 'struct bar'
 struct bar : base<bar> {
        ^~~
Run Code Online (Sandbox Code Playgroud)

如何声明bar::fooin 的返回类型的别名base …

c++ crtp decltype c++11 declval

12
推荐指数
1
解决办法
229
查看次数

标签 统计

c++ ×2

c++11 ×2

crtp ×1

decltype ×1

declval ×1

lambda ×1

metaprogramming ×1

traits ×1