基于if子句的c++模板实例化

C++ template instantiation depending on if clause

本文关键字:实例化 c++ if 子句 基于      更新时间:2023-10-16

此刻我正在做:

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

但是我想做:

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

我不能这样做,因为c++想要模板实例化的const变量。然而,有那么一种方法可以做到吗?

你可以用模板形参定义一个函数:

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

:

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

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

你也可以这样做:

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