首页 > 解决方案 > 不在 C++ 模板参数中使用 constexpr

问题描述

我正在使用类型变量itk::Image<OutputPixelType, Dimension>,其中“itk”来自图像处理库 ITK。

以下代码编译:

constexpr unsigned int Dimension = 3;
using PixelType = float; 
using MyImageType = itk::Image<PixelType, Dimension>;

但现在我需要将“维度”定义为从函数计算的东西。

unsigned int Dimension = get_dimension(...);

我的编译器给出了一个错误:

error: non-type template argument is not a constant expression
  using MyImageType = itk::Image<PixelType, Dimension>;
                                            ^~~~~~~~~

我该如何解决这个问题?我希望使用“维度”作为从函数计算的东西。

标签: c++c++11templatesconstexpritk

解决方案


您的get_dimension功能应该是constexpr,如果是这种情况,您可以拥有以下内容:

constexpr unsigned int Dimension = get_dimension(...);

例子

假设您有以下简化类:

template <int v>
class Foo {
public:
    constexpr Foo()
        : v_(v)
    {}

private:
    int v_;
};

然后是以下内容:

int v = get();
using FooInt = Foo<v>;

其中get函数定义如下:

int get() {
    return 1;
}

您将得到与示例中相同的错误。

因此,解决方案是标记get函数constexpr并使v值也constexpr像:

constexpr int get() {
    return 1;
}

constexpr int v = get();
using FooInt = Foo<v>;

看看演示

更新

为了能够使用模板,编译器需要在编译时知道模板参数,因此,如果Dimension不是一个constexpr(声明可以在编译时对变量的值求值)变量,则不能使用作为模板参数。


推荐阅读