在默认lambda参数中访问模板类参数 [英] Access template class parameter in default lambda argument

查看:146
本文介绍了在默认lambda参数中访问模板类参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个简单的通用池。模板类在构造函数中使用一个参数,它是一个工厂函数,可根据需要实例化池中的对象。

I'm writing a simple universal pool. The template class takes a parameter in the constructor that is a factory function to instantiate objects in the pool as needed.

template<typename T>
struct Foo {
    std::function <T*()> factory_;
    Foo(std::function<T*()> factory): factory_(factory) {}
};

这个编译很好,但我想使用lambda创建一个默认参数:

This compiles fine, but I wanted to make a default argument for the constructor using lambda:

Foo(std::function<T*()> factory = [](){return new T();} ): factory_(factory) {}

这不会编译 - 它说T是未知的。有没有办法让lambda表达式知道类模板参数?我尝试使用 typedef ,但没有效果。

This does not compile - it says that T is unknown. Is there a way to make lambda expressions aware of class template parameters? I tried using typedef, but to no avail.

推荐答案

按照建议工作,但是你可能在VC ++中遇到了一个错误(它不完全是C ++ 11准备好的)。

This should work as proposed, however you might have hit a bug in VC++ (it's not exactly C++11 ready yet).

作为一种解决方法,你可以尝试替换

As a workaround, you might try to replace your lambda by a private static method instead.

template <typename T>
class LIFOPool
{
    std::function <T*()> factory_;
    //...details irrelevant

    static T* DefaultMake() { return new T{}; }
public:
    LIFOPool(std::function<T*()> factory = DefaultMake) : factory_(factory) {}
    //...details irrelevant
};

这篇关于在默认lambda参数中访问模板类参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆