Creating an instance of a C ++ template depending on if statement

At the moment I am doing:

if(dimension == 2) { typedef itk::Image<short, 2> ImageType; typedef itk::Image<unsigned int, 2> IntegralImageType; m_pApp->train<2, ImageType, IntegralImageType>(); } else { typedef itk::Image<short, 3> ImageType; typedef itk::Image<unsigned int, 3> IntegralImageType; m_pApp->train<3, ImageType, IntegralImageType>(); } 

But I would like to do:

  if (dimension == 2) DIMENSION = 2; else DIMENSION = 3; typedef itk::Image<short, DIMENSION> ImageType; typedef itk::Image<unsigned int, DIMENSION> IntegralImageType; m_pApp->train<DIMENSION, ImageType, IntegralImageType>(); 

I failed to do this because C ++ requires constant variables to instantiate the template. Is there any way to do this nonetheless?

+6
source share
2 answers

You can define a function with a template parameter:

 template<unsigned N> void train(){ typedef itk::Image<short, N> ImageType; typedef itk::Image<unsigned int, N> IntegralImageType; m_pApp->train<N, ImageType, IntegralImageType>(); } 

then

 if (dimension == 2) train<2>(); else train<3>(); 

Please note that this code will create both templates (the code will be generated for them), since during compilation there is no way to find out which one will be used.

+11
source

You can also do something like this:

 const int N = DIMENSION == 2 ? 2 : 3; typedef itk::Image<short, N> ImageType; typedef itk::Image<unsigned int, N> IntegralImageType; m_pApp->train<N, ImageType, IntegralImageType>(); 
-1
source

Source: https://habr.com/ru/post/901791/


All Articles