c++ - 不在 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>;
^~~~~~~~~
我该如何解决这个问题?我希望使用“维度”作为从函数计算的东西。
解决方案
您的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
(声明可以在编译时对变量的值求值)变量,则不能使用作为模板参数。
推荐阅读
- r - 在R数据框中提取大于某些值的列
- c - 如何添加不断询问用户输入并将所有输入保存到文件
- c# - 如何确保从 taskList 调用的方法不会同时执行?
- python - 将多级多索引名称转换为 DataFrame 列,Python 3.6
- python - python脚本问题-语法无效
- django - Django用不同的字段注册两种不同类型的用户
- angular - 在 Angular-CLI 中设置操作系统环境变量
- javascript - 带有离线 JavaScript 的 PWA
- javascript - 如何使日期输入字段的默认值成为普通文本?
- oracle-apex - APEX 如何创建允许您为单个用户创建用户名和密码的页面