2015-01-09 107 views
2

我想爲std::function<T(Variable nums of arguments)>創建一個模板,該模板通過調用默認構造函數來返回類的默認值。C++ 11:用於調用類型的默認構造函數的variadic lambda模板

我嘗試這樣做:

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()>)' ...

回答

6

如果沒有明確的模板參數列表,則不能直接調用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