我正在使用 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>;
^~~~~~~~~
我该如何解决这个问题?我希望使用“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>;
看看demo
更新
为了能够使用模板,编译器需要在编译时知道模板参数,因此,如果Dimension
不是constexpr
(它声明它可以在编译时评估变量的值)变量,它不能用作模板参数。
关于c++ - 在 C++ 模板参数中不使用 constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61520212/