Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在编译时将整数模板参数修改为非零?_C++_Templates_Compile Time - Fatal编程技术网

C++ 如何在编译时将整数模板参数修改为非零?

C++ 如何在编译时将整数模板参数修改为非零?,c++,templates,compile-time,C++,Templates,Compile Time,如果我有此代码: template<int SIZE = 0> class A { public: union { int buf[MagicThing]; /* ... */ }; }; 模板 甲级{ 公众: 联合{ int buf[MagicThing]; /* ... */ }; }; 在C++中,可以使用一些(宏)称为MigICTION的方法来工作: 如果大小>0,则MagicThing==大小 如果大小==0,则Mag

如果我有此代码:

template<int SIZE = 0>
class A {
public:

    union {
        int buf[MagicThing];
        /* ... */
    };
};
模板
甲级{
公众:
联合{
int buf[MagicThing];
/* ... */
};
};
在C++中,可以使用一些(宏)称为MigICTION的方法来工作:

  • 如果大小>0,则MagicThing==大小
  • 如果大小==0,则MagicThing==1
在编译时? (最好是一些不需要使用boost库等的小技巧)

您可以使用:

int buf[SIZE > 0 ? SIZE : 1];
你可以试试这个

int buf[SIZE == 0 ? 1 : SIZE]
并使
SIZE
无符号,或添加
static\u assert
以检查大小是否为非负。当
SIZE
小于0时,您没有指定所需的行为。大概不会发生这种情况。

(如果大小始终为0或更多,请将其类型更改为unsigned。)

一个疯狂的示例解决方案,它可能可以作为其他情况的想法(使用C++11的资源):


如果大小<0怎么办?条件是“if SIZE>0那么MagicThing=SIZE,if SIZE=0 MagicThing=1”,未指定,因此特定于实现:-)(在我的例子中是1)。@jarod42真是浪费。你可以调用鼻魔。未签名通常是一个坏主意,因为标准命令会将负值悄悄地转变为巨大的正值,这很少是一个好计划。@Yakk我同意,而简单的
静态断言
可能是一个好选择。另一方面,通常使用
std::size\t
来表示尺寸。因此可以使用一个无符号整数和一个
static\u assert
检查大小是否小于某个最大值。
#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
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);
   }
};