C ++ 11:用于调用类型的默认构造函数的可变参数lambda模板

时间:2021-04-01 18:57:11

I want to create a template for a std::function<T(Variable nums of arguments)> that returns the default value of a class by calling the default constructor.

我想为std :: function 创建一个模板,它通过调用默认构造函数来返回类的默认值。 (variable>

I tried this:

我试过这个:

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

I want to use it in occasions where you just need the default value and no complicated function, for instance in my Image<T> class:

我想在你只需要默认值而没有复杂功能的情况下使用它,例如在我的Image 类中:

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));
            }
        }
    }
    ...
};

to clear an image I could just call:

清除我可以打电话的图像:

image.drawEachPixel(zero());

when compiling I get the error no matching function for call to 'Image<unsigned char>::drawEachPixel(std::function<unsigned char()>)'...

在编译时我得到错误没有匹配函数来调用'Image :: drawEachPixel(std :: function )'...

1 个解决方案

#1


6  

You can't just call zero without an explicit template argument list. It has template parameters:

没有显式模板参数列表,您不能只调用零。它有模板参数:

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

The template arguments cannot be deduced, so the template parameters stay without corresponding types.
Instead, use a conversion operator template:

无法推导出模板参数,因此模板参数保持不相应的类型。而是使用转换运算符模板:

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

And use it as before. Demo.

并像以前一样使用它。演示。

#1


6  

You can't just call zero without an explicit template argument list. It has template parameters:

没有显式模板参数列表,您不能只调用零。它有模板参数:

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

The template arguments cannot be deduced, so the template parameters stay without corresponding types.
Instead, use a conversion operator template:

无法推导出模板参数,因此模板参数保持不相应的类型。而是使用转换运算符模板:

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

And use it as before. Demo.

并像以前一样使用它。演示。