如何在编译时将整数模板参数修改为非零值
How to modify integer template argument to nonzero at compile time?
如果我有这个代码:
template<int SIZE = 0>
class A {
public:
union {
int buf[MagicThing];
/* ... */
};
};
在C++中可以制作一些称为MagicThing的(宏?)以这种方式工作的:
- 如果大小> 0,则魔术事物==大小
- 如果大小 == 0,则魔术事物 == 1
在编译时?(理想情况下,一些简短的技巧,无需使用增强库等)
您可以使用
:
int buf[SIZE > 0 ? SIZE : 1];
你可以试试这个
int buf[SIZE == 0 ? 1 : SIZE]
并将SIZE
设为无符号,或添加static_assert
以检查大小是否为非负数。您没有指定当SIZE
小于 0 时想要的行为。大概这不应该发生。
(如果 SIZE 始终为 0 或更大,请将其类型更改为无符号。
一个疯狂的示例解决方案,也许可以用作其他情况的想法(使用 C++11 的资源):
#include <iostream>
/* General case */
template<unsigned SIZE>
constexpr unsigned MagicThing()
{
return SIZE;
}
/* Partial specialization when SIZE == 0 */
template<>
constexpr unsigned MagicThing<0>()
{
return 1;
}
template<unsigned SIZE = 0>
class A {
public:
int buf[MagicThing<SIZE>()];
size_t size() const
{
return sizeof(buf) / sizeof(int);
}
};
int main()
{
A<0> a0;
A<1> a1;
A<5> a5;
std::cout << a0.size() << " " << a1.size() << " " << a5.size() << std::endl;
}
/* Compilation and execution */
$ gcc -std=c++11 sample.cpp
$ ./a.out
1 1 5
其他(不是最简单的)可能性是,使用新的static_if
指令,为以下标准C++14提出,下一个(我不确定我的语法是否正确):
template<unsigned SIZE = 0>
class A {
public:
static_if (SIZE > 0)
int buf[SIZE];
else
int buf[1];
size_t size() const
{
return sizeof(buf) / sizeof(int);
}
};
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 修改函数中的指针(将另一个指针作为参数传递)
- 如果返回 -1,时间() 的参数是否被修改?
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 通过非常量引用参数修改常量引用参数
- 如何在使用 Qt5 构造函数时将非常量参数修改为常量参数?
- 如何接受可修改和不可修改的参数?
- 为什么我应该在scanf()-家族成员中包含一个长度修饰符作为参数?有什么好处?使用长度修改器进行扫描的作用
- 将参数从C/C++JNI传递给Java,得到修改后的值
- 如何修改此函数,以便如果函数的参数是特定结构,则返回具有较大整数的结构?
- 通过运算符使用标量参数重写来修改类成员
- 修改"参数视图属性"面板 (5.7.0) 上的默认属性
- 为什么 QObject::d isconnect(const QMetaObject::Connection &connection) 采用 const 参数并打算修改它?
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 修改嵌套 lambda 中捕获的参数:gcc 与 clang?
- accept(..) 似乎正在修改我给它的文件描述符参数
- 是否允许删除以修改其参数
- 如何在编译时将整数模板参数修改为非零值
- C++,如何用新的参数修改正在执行的程序
- 如何通过参数修改指针