Initializer_list用于预定义大小的数组
initializer_list for arrays with predefined sizes
假设我们想使用c++的initializer_list来表示一些用户定义的类型,该类型表示预定义大小的数组(在编译时知道)。例如,矩阵的索引(行、列):
#include <initializer_list>
#include <algorithm>
#include <assert.h>
using idx_t = unsigned;
class MatrixIdx {
public:
MatrixIdx() :
_idx { 0, 0 }
{}
// this is how I'm able to use initializer list for now
// cons:
// * run-time assertion
// * additional header (algorithm)
// * not in member initializer list (call me perfectionist)
//
MatrixIdx(std::initializer_list<idx_t> l)
{
assert(l.size() == 2);
std::copy(l.begin(), l.end(), _idx);
}
//I want to achive constructor similiar to this one
//Won't compile
//
//MatrixIdx(std::initializer_list<idx_t> l) :
//static_assert(l.size() == 2, "two elements expected") //compile time assertion
//_idx[0] ( l[0] ),
//_idx[1] ( l[1] )
//{}
idx_t row() { return _idx[0]; }
void setRow(const idx_t i) { _idx[0] = i; }
idx_t col() { return _idx[1]; }
void setCol(const idx_t i) { _idx[1] = i; }
private:
idx_t _idx[2];
};
int main(void)
{
MatrixIdx idx; //default - OKAY
//MatrixIdx idxIL { 1, 2 }; //this should compile
//this should emit human-readable compile-time error
//MatrixIdx idxILError { 1, 2, 3 };
return 0;
}
实现这一目标的最佳方法是什么?
功劳应该归功于@IgorTandetnik,他提供了与op评论相同的答案。
对于您的情况,可以非常简单地采用统一初始化语法,只需提供一个接受两个类型为idx_t
的参数的构造函数。
class MatrixIdx {
public:
...
MatrixIdx() : ... {}
MatrixIdx(idx_t, idx_t) : ... {}
};
在主代码中:
int main()
{
MatrixIdx mat {}; // Okay
MatrixIdx mat {1,2}; // Okay
MatrixIdx mat {1,2,3}; // Error - no 3-arg. c'tor for MatrixIdx
}
相关文章:
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- C++编程从外部文本文件定义数组大小
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 删除动态数组时未定义标识符
- 在定义字符数组(井字游戏)的 for 循环中应用输入限制
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 如何使用自定义类型声明Arduino数组?
- 自定义 STL 兼容迭代器,用于迭代 2D 数组类的列
- 如何访问宏中定义的数组元素
- 为什么我的 2D 数组未定义?
- shared_ptr<>到数组自定义删除器(带make_shared)
- const 数组,用于在数组长度定义中使用其元素或为模板参数提供值
- C++数组类定义和实现,未在作用域中声明
- 在头文件的数组中定义资源 ID
- 如何处理C++中在数组上定义的函数
- c++和Java数组声明/定义:差异
- C++ 我知道数组长度,但想知道是否是一种更简洁的数组元素定义方法
- 使用C++数组输入定义重载函数是安全的
- 堆积或堆叠数组.用户定义的类型难题
- 通过无符号整数读取无符号字符数组未定义,因此不安全