2012-11-29 46 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>的一些变体。

相关问题