[英]How to modify integer template argument to nonzero at compile time?
如果我有此代碼:
template<int SIZE = 0>
class A {
public:
union {
int buf[MagicThing];
/* ... */
};
};
在C ++中可以制作一些(宏?)稱為MagicThing的方式,這種方式可以這樣工作:
在編譯時? (理想情況下是一些小技巧,無需使用Boost庫等。)
您可以使用:
int buf[SIZE > 0 ? SIZE : 1];
你可以試試這個
int buf[SIZE == 0 ? 1 : SIZE]
然后將SIZE
無符號,或者添加static_assert
來檢查大小是否為負數。 您沒有指定當SIZE
小於0時想要什么行為。大概不應該發生這種情況。
(如果SIZE始終為0或更大,請將其類型更改為unsigned。)
一個瘋狂的示例解決方案,可能可以用作其他情況的想法(使用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);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.