有没有办法在一定范围内强制使用模板参数?
Is there a way to force a template argument within a certain range?
请原谅,我已经尝试搜索了,也许我只是使用了错误的关键字。我几乎肯定有一种方法可以将整数模板参数绑定到正值。我只是从痛苦的经历中知道它可能根本不直观。
如你所知,用于执行此操作的 STL 小部件(如果有这样的动物)几乎与 table 相去甚远,因为尽管我喜欢 STL,但我不能将 STL 用于代码我的目标是定义之外的次要内容,因为我使用此代码定位的许多平台都没有它。 (32kb 机器等)
基本上我要的就是这个
template<const size_t TCapacity /* bounded to a minimum of one */ > class Buffer {
...
};
如果 TCapacity 为零,则抛出编译错误
Buffer<0> buffer; // won't compile
我的意思是,我认为我不仅以前遇到过这种巫术,而且我还看到像 Spirit 框架这样的东西可以做更复杂的事情,所以我很确定有一个答案。我只是怀疑这是否显而易见。
提前致谢!
template<std::size_t cap> requires(cap >= 1) class Buffer;
我怀疑它在 C++11 中是否可靠。当然,你可以使用一些前置概念SFINAE,比如
template<std::size_t cap, class = std::enable_if_t<(cap > 0)>> class Buffer;
甚至更做作的东西,比如
template<std::size_t cap> class Buffer
: private std::enable_if_t<(cap > 0)
, std::integral_constant<std::size_t, cap>>> {};
但是可以通过
之类的东西轻松克服它们
template<> class Buffer<0> {};
在 C++11 中,您可以在 class:
中使用 static_assert
template<std::size_t TCapacity> class Buffer
{
static_assert(TCapacity > 0, "The size must be greater than zero");
// ...
};
如果表达式为真,则此声明无效。否则会发出编译时错误,并且文本包含在诊断消息中。
请原谅,我已经尝试搜索了,也许我只是使用了错误的关键字。我几乎肯定有一种方法可以将整数模板参数绑定到正值。我只是从痛苦的经历中知道它可能根本不直观。
如你所知,用于执行此操作的 STL 小部件(如果有这样的动物)几乎与 table 相去甚远,因为尽管我喜欢 STL,但我不能将 STL 用于代码我的目标是定义之外的次要内容,因为我使用此代码定位的许多平台都没有它。 (32kb 机器等)
基本上我要的就是这个
template<const size_t TCapacity /* bounded to a minimum of one */ > class Buffer {
...
};
如果 TCapacity 为零,则抛出编译错误
Buffer<0> buffer; // won't compile
我的意思是,我认为我不仅以前遇到过这种巫术,而且我还看到像 Spirit 框架这样的东西可以做更复杂的事情,所以我很确定有一个答案。我只是怀疑这是否显而易见。
提前致谢!
template<std::size_t cap> requires(cap >= 1) class Buffer;
我怀疑它在 C++11 中是否可靠。当然,你可以使用一些前置概念SFINAE,比如
template<std::size_t cap, class = std::enable_if_t<(cap > 0)>> class Buffer;
甚至更做作的东西,比如
template<std::size_t cap> class Buffer
: private std::enable_if_t<(cap > 0)
, std::integral_constant<std::size_t, cap>>> {};
但是可以通过
之类的东西轻松克服它们template<> class Buffer<0> {};
在 C++11 中,您可以在 class:
中使用static_assert
template<std::size_t TCapacity> class Buffer
{
static_assert(TCapacity > 0, "The size must be greater than zero");
// ...
};
如果表达式为真,则此声明无效。否则会发出编译时错误,并且文本包含在诊断消息中。