[Insight-users] template at runtime

Peter Cech pcech at vision.ee.ethz.ch
Wed, 31 Mar 2004 00:52:43 +0200


On Tue, Mar 30, 2004 at 14:45:18 -0700, Corinne Mattmann wrote:
> Hi,
> 
> I would like to write an application for two different image types. This
> means that I get an image - in my case from vtk - and then I would like
> to define an itkImageType depending on this image
> (vtkImageData->GetScalarType()). I tried to use the switch command:
> 
>   switch(aimReader_Image1->GetOutput()->GetScalarType()){
>   case VTK_CHAR:
>     typedef itk::Image<char, Dimension> ImageType;
>     break;
>   case VTK_SHORT:
>     typedef itk::Image<short, Dimension> ImageType;
>     break;
>   default:
>     typedef itk::Image<short, Dimension> ImageType;
>     break;
>   }
> 
> But this results in the following error:
> 
> error C2371: 'ImageType' : redefinition; different basic types
> 
> 
> How can I solve this problem?

Hi,

switch body is a single scope, hence the error. Typedef is compile-time
construct thus ImageType cannot be typedefed at run-time as you tried.
However, you can rewrite the code like this:

  switch(aimReader_Image1->GetOutput()->GetScalarType()){
  case VTK_CHAR:
    {
      typedef itk::Image<char, Dimension> ImageType;
      // do all the computation with ImageType
    }
    break;
  case VTK_SHORT:
  default:
    {
      typedef itk::Image<short, Dimension> ImageType;
      // do all the computation with ImageType
    }
    break;
  }

To avoid unnecessary code duplication, put "all the computation with
ImageType" into a template function. That's how I do it myself.

Regards,
Peter Cech