没有默认构造函数的重复元素的模板化数组
templated array of duplicate elements without default constructor
当元素类型没有默认构造函数时,有没有办法用所有重复元素构造一个模板化的元素数组?
我尝试了以下方法:
template<typename T, int n> struct Array {
template<typename... Args> explicit Array(const T& arg1, Args... args)
: m_a{arg1, args...} { }
static Array<T,n> all(const T& value) {
Array<T,n> ar; // error: use of deleted function 'Array<TypeWithoutDefault, 10>::Array()'
for (int i=0; i<n; i++)
ar.m_a[i] = value;
return ar;
}
T m_a[n];
};
struct TypeWithoutDefault {
TypeWithoutDefault(int i) : m_i(i) { }
int m_i;
};
int main() {
// works fine
Array<TypeWithoutDefault,2> ar1 { TypeWithoutDefault{1}, TypeWithoutDefault{2} };
(void)ar1;
// I want to construct an Array of n elements all with the same value.
// However, the elements do not have a default constructor.
Array<TypeWithoutDefault,10> ar2 = Array<TypeWithoutDefault, 10>::all(TypeWithoutDefault(1));
(void)ar2;
return 0;
}
以下内容将解决您的问题:
#if 1 // Not in C++11
template <std::size_t ...> struct index_sequence {};
template <std::size_t I, std::size_t ...Is>
struct make_index_sequence : make_index_sequence<I - 1, I - 1, Is...> {};
template <std::size_t ... Is>
struct make_index_sequence<0, Is...> : index_sequence<Is...> {};
#endif
namespace detail
{
template <typename T, std::size_t ... Is>
constexpr std::array<T, sizeof...(Is)> create_array(T value, index_sequence<Is...>)
{
// cast `Is` to `void` to remove the warning: unused value
// and avoid possible "evil" overload of `operator ,` (comma).
return {{(static_cast<void>(Is), value)...}};
}
}
template <std::size_t N, typename T>
constexpr std::array<T, N> create_array(const T& value)
{
return detail::create_array(value, make_index_sequence<N>());
}
所以测试一下:
struct TypeWithoutDefault {
TypeWithoutDefault(int i) : m_i(i) { }
int m_i;
};
int main()
{
auto ar1 = create_array<10>(TypeWithoutDefault(42));
std::array<TypeWithoutDefault, 10> ar2 = create_array<10>(TypeWithoutDefault(42));
return 0;
}
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int