在c++模板参数中未使用constexpr

Not using constexpr in c++ template arguments

本文关键字:未使用 constexpr 参数 c++      更新时间:2024-04-28

我正在处理一个类型为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>;
^~~~~~~~~

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

您的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(它声明可以在编译时评估变量的值(变量,则不能将其用作模板参数。