在 C++ 模板参数中不使用 constexpr

zel*_*ell 2 c++ templates constexpr itk c++11

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

以下代码编译:

constexpr unsigned int Dimension = 3;
using PixelType = float; 
using MyImageType = itk::Image<PixelType, Dimension>;
Run Code Online (Sandbox Code Playgroud)

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

unsigned int Dimension = get_dimension(...);
Run Code Online (Sandbox Code Playgroud)

我的编译器报错:

error: non-type template argument is not a constant expression
  using MyImageType = itk::Image<PixelType, Dimension>;
                                            ^~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

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

Nut*_*ker 7

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

constexpr unsigned int Dimension = get_dimension(...);
Run Code Online (Sandbox Code Playgroud)

例子

假设您有以下简化类:

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

private:
    int v_;
};
Run Code Online (Sandbox Code Playgroud)

然后是以下内容:

int v = get();
using FooInt = Foo<v>;
Run Code Online (Sandbox Code Playgroud)

其中get函数定义如下:

int get() {
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

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

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

constexpr int get() {
    return 1;
}

constexpr int v = get();
using FooInt = Foo<v>;
Run Code Online (Sandbox Code Playgroud)

看一下演示

更新

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