(如果大小將始終爲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);
}
};
哦,我很笨:-),謝謝! – user3123061
如果SIZE <0,該怎麼辦?條件是「如果SIZE> 0,那麼MagicThing = SIZE,如果SIZE = 0 MagicThing = 1」 –
未指定,因此實現特定:-)(在我的情況下爲1)。 – Jarod42