c++0x 中模板参数的编译时边界
compile time bounding of template parameters in c++0x
这里是一个严重过度简化的 class:
template <unsigned x>
class myArray {
int getIndex(unsigned i) { return y[i]; }
void setIndex(unsigned i, int v) { y[i] = v; }
private:
int y[x];
};
我如何使用模板元编程来确保 x
小于 64
( 或任意值 )?
我可以添加构造函数:
myArray () { if (x >= 64) { throw; } }
但这太可怕了...
有没有更优雅的方法来绑定模板参数,以便在编译时而不是运行时检查?
NOTE: If this is possible in c++03
, then I need the syntax in that form (in case it were to differ from c++11
).
更新
我根据以下 SO post...
提供的示例得出了一个解决方案
C compiler asserts - how to implement?
C++11 及以上
在 C++11 及更高版本中有用于此目的的 static_assert
声明。然后,您的编译器会在编译时检查条件。您可以在 class 范围内以
形式使用它
template <unsigned x>
class myArray {
static_assert(x > 0 && x <= 64, "array size in (0, 64]");
};
C++11 之前
在 C++11 之前的版本中,有一些解决方法可以提供与 C++11 static_assert
相同的功能。大多数这些解决方法都提供了一个基于以下想法的宏:如果您的检查(bool
类型的编译时表达式)产生 false
,那么该宏将扩展为一些产生编译错误的非法代码。否则,宏将扩展为空字符串。高级实现允许指定额外的错误消息。如果你想要一个开箱即用的解决方案,那么你可以看看 BOOST_STATIC_ASSERT
.
这里是一个严重过度简化的 class:
template <unsigned x>
class myArray {
int getIndex(unsigned i) { return y[i]; }
void setIndex(unsigned i, int v) { y[i] = v; }
private:
int y[x];
};
我如何使用模板元编程来确保 x
小于 64
( 或任意值 )?
我可以添加构造函数:
myArray () { if (x >= 64) { throw; } }
但这太可怕了...
有没有更优雅的方法来绑定模板参数,以便在编译时而不是运行时检查?
NOTE: If this is possible in
c++03
, then I need the syntax in that form (in case it were to differ fromc++11
).
更新
我根据以下 SO post...
提供的示例得出了一个解决方案C compiler asserts - how to implement?
C++11 及以上
在 C++11 及更高版本中有用于此目的的 static_assert
声明。然后,您的编译器会在编译时检查条件。您可以在 class 范围内以
template <unsigned x>
class myArray {
static_assert(x > 0 && x <= 64, "array size in (0, 64]");
};
C++11 之前
在 C++11 之前的版本中,有一些解决方法可以提供与 C++11 static_assert
相同的功能。大多数这些解决方法都提供了一个基于以下想法的宏:如果您的检查(bool
类型的编译时表达式)产生 false
,那么该宏将扩展为一些产生编译错误的非法代码。否则,宏将扩展为空字符串。高级实现允许指定额外的错误消息。如果你想要一个开箱即用的解决方案,那么你可以看看 BOOST_STATIC_ASSERT
.