2017-08-16 55 views
1

我使用模板的模板參數如下:C++ 11轉發模板的模板參數不起作用

/* [1]: Definition containing a template template parameter */ 
      template <typename T, template<class> class Kernel> 
      void ForEach(Kernel<T> kernel, T * pSrc, int elementCount) { 
       //.... 
      } 

    /* [2]: Definition of a helper struct */ 
      template <typename T> struct KernelStd { 
       //... 
      }; 

    /* [3]: Use the previous definitions */ 
      float arr1[5] = {1,2,3,4,5}; 

      //The following two calls to ForEach do successfully compile 
      ForEach(KernelStd<float>(), arr1, 5); //USE1 
      ForEach<float>(KernelStd<float>(), arr1, 5); //USE2 

    /* [4]: Definition of a helper function */  
      template <typename F, typename ...Args> 
      void forwarder(F func1, Args && ...args) { 
       //... 
       func1(std::forward<Args>(args)...); 
      } 
      //But the following callS do not compile. 
      forwarder(ForEach, KernelStd<float>(), arr1, 5); //USE3 
      forwarder(ForEach<float>, KernelStd<float>(), arr1, 5); //USE4 

我使用VS2013更新5,我得到以下錯誤:

  error C2783: 'void ForEach(Kernel<T>,T *,int)' : could not deduce 
     template argument for 'Kernel' 

任何幫助將不勝感激。

+0

什麼是ForEach?它在某種程度上與「轉化」有關嗎?什麼是KernelStd?它是否以某種方式與'Kernel1'相關?如果你顯示[一個MCVE](https://stackoverflow.com/help/mcve) –

+0

謝謝你指出我的代碼片段中的錯誤。我已經修復了這些。 – fonishormon

回答

0

forwarder是一個函數,所以它的第一個參數必須是F類型的實體(對象或函數)。

ForEach既不是一個功能也不是一個對象,它是一個模板。因此,您無法將ForEach傳遞給forwarder

ForEach<float>未傳遞足夠的模板參數以完全識別從ForEach模板實例化的函數。由於模板參數的扣除,您可以在調用函數模板時避開它。但是在forwarder的背景下,F應該從第一個參數中推導出來,所以你有點雞和雞蛋的問題。

如果要使用forwarder,則必須爲其提供實際功能,而不是使用模板。所以,你不得不這樣做:

forwarder(ForEach<float, KernelStd>, KernelStd<float>(), arr1, 5); 

ForEach<float, KernelStd>包含所有模板參數,因此它指定一個功能(從模板實例化)。