2012-11-29 43 views
0

即使通過明確提的是,在函數指針參數是常量,它似乎並沒有能夠將函數轉換爲這種類型:無法將具有常量參數的函數轉換爲函數指針?

#include <iostream> 

template <typename T> 
class Image{}; 

template <typename TPixel> 
static void 
FillImage(const Image<TPixel>* const image){} 
//FillImage(Image<TPixel>* const image){} // Replacing the above line with this one compiles fine 

int main() 
{ 
    typedef Image<float> ImageType; 
    ImageType* image = new ImageType; 
    void (*autoFunctionPointer)(const decltype(image)) = FillImage; 
    autoFunctionPointer(image); 
} 

誰能解釋如何使它做到這一點的轉換?

+0

您錯過了一個'const',目前參數擴展爲'ImageType * const'。你不能通過'decltype'輕鬆搞定。 – Xeo

+0

如果你正在使用C++ 11,爲什麼不只是'auto'? – leftaroundabout

+0

@leftaroundabout - 我指定我想使用的過載(見http://stackoverflow.com/questions/13632507/how-to-get-a-function-pointer-to-the-overloaded-function-that編譯器選擇更多細節)。 –

回答

1

const適用於指針。

所以,如果你改變image

const ImageType* image = new ImageType; 

FillImage()作品的第一個版本如預期const decltype(image)相當於ImageType* constconst ImageType*

爲了得到一個const ImageType*可以使用std::remove_pointer

#include <type_traits> 
... 
void (*autoFunctionPointer)(const std::remove_pointer<decltype(image)>::type *) = FillImage; 
+0

那麼如何獲得'const ImageType *'呢? –

+0

@DavidDoria:嘗試'const decltype(* image)* const'。 – GManNickG

+1

@GManNickG這不起作用,因爲'decltype(* image)'的類型是'ImageType&',而你不能定義'ImageType&const'。 –

0

FillImage是一個模板,而不是一個函數。嘗試一下FillImage<float>的一些變體。

相關問題