C++模板实例化取决于if子句

Flo*_*bes 6 c++ templates

目前我正在做:

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>();
}
Run Code Online (Sandbox Code Playgroud)

但我想这样做:

    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>();
Run Code Online (Sandbox Code Playgroud)

我无法做到这一点,因为c ++需要const变量用于模板实例化.有没有这样的方法呢?

Jam*_*mes 11

您可以使用模板参数定义函数:

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

然后:

if (dimension == 2)
    train<2>();
else
    train<3>();
Run Code Online (Sandbox Code Playgroud)

请注意,此代码将实例化两个模板(将为它们生成代码),因为在编译时无法知道将使用哪个模板.