【问题标题】:C++11: variadic lambda template for calling the default constructor of a typeC ++ 11:variadic lambda模板,用于调用类型的默认构造函数
【发布时间】:2015-03-08 08:01:08
【问题描述】:

我想为std::function<T(Variable nums of arguments)> 创建一个模板,该模板通过调用默认构造函数返回类的默认值。

我试过了:

template <class T,class... Args> inline std::function<T(Args...)> zero(){
    return [](Args...){ return T();};
}

我想在你只需要默认值而不需要复杂函数的场合使用它,例如在我的Image&lt;T&gt; 类中:

template <typename T> class Image{
    ...
    void drawEachPixel(std::function<T(size_t,size_t)> func){
        forRange(x,w){
            forRange(y,h){
                this->setPixel(x,y,func(x,y));
            }
        }
    }
    ...
};

要清除我可以调用的图像:

image.drawEachPixel(zero());

编译时出现错误no matching function for call to 'Image&lt;unsigned char&gt;::drawEachPixel(std::function&lt;unsigned char()&gt;)'...

【问题讨论】:

    标签: c++ templates c++11 lambda variadic-templates


    【解决方案1】:

    你不能只调用zero 而没有明确的模板参数列表。它有模板参数:

    template <class T, class... Args>
    //        ^^^^^^^^^^^^^^^^^^^^^^
    inline std::function<T(Args...)> zero()
    

    模板参数不能推导,所以模板参数没有对应的类型。
    相反,使用转换运算符模板:

    struct Zero
    {
         template <typename T, typename... Args>
         operator std::function<T(Args...)> ()
         {
             return [] (Args...) { return T(); };
         }
    };
    

    并像以前一样使用它。 Demo.

    【讨论】:

      猜你喜欢
      • 2011-03-27
      • 2014-02-05
      • 2019-09-29
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多