Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template instantiation depending on if clause

Tags:

c++

templates

At the moment I'm 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 wasn't able to do it because c++ wants const variables for the template instantiation. Is there so way to do it nevertheless?

like image 533
Flobbes Avatar asked Nov 18 '11 08:11

Flobbes


1 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>();

Note that this code will instantiate both templates (code will be generated for them), since at compile-time there is no way to know which one will be used.

like image 51
James Avatar answered Oct 18 '22 20:10

James