我想为 std::function<T(Variable nums of arguments)>
创建一个模板通过调用默认构造函数返回类的默认值。
我试过这个:
template <class T,class... Args> inline std::function<T(Args...)> zero(){
return [](Args...){ return T();};
}
我想在只需要默认值而不需要复杂功能的情况下使用它,例如在我的 Image<T>
中类:
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<unsigned char>::drawEachPixel(std::function<unsigned char()>)'
...
最佳答案
如果没有显式模板参数列表,您不能只调用 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 .
关于C++11:用于调用类型的默认构造函数的可变参数 lambda 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27870051/