相关疑难解决方法(0)

我必须在何处以及为何要使用"模板"和"typename"关键字?

在模板,在那里,为什么我必须把typenametemplate上依赖的名字呢?究竟什么是依赖名称?我有以下代码:

template <typename T, typename Tail> // Tail will be a UnionNode too.
struct UnionNode : public Tail {
    // ...
    template<typename U> struct inUnion {
        // Q: where to add typename/template here?
        typedef Tail::inUnion<U> dummy; 
    };
    template< > struct inUnion<T> {
    };
};
template <typename T> // For the last node Tn.
struct UnionNode<T, void> {
    // ...
    template<typename U> struct inUnion {
        char fail[ -2 + (sizeof(U)%2) ]; // Cannot be instantiated for any …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++-faq dependent-name typename

1061
推荐指数
8
解决办法
15万
查看次数

是否有可能找出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万
查看次数