[英]How to limit char array length in constructor
使用扩展嵌入式Cpp。 如何在发布版本中的编译错误中生成此结果:
Param okParam("Yeah!"); // this line should be ok
Param nOkParam("REEEEEEEEEEE"); // too big array, not ok. compiler error.
哪里:
int const c_max = 10;
template<int N>
struct Param
{
char value[c_max];
Param(char const (&p_value)[N])
{
memcpy(value, p_value, sizeof(p_value));
}
};
我不认为你可以模板化构造函数,所以整个结构需要模板化,对吧?
我希望这提供一个干净的编译器错误,以便使用它的人会立即注意到它。
我们的扩展嵌入式C ++版本不提供任何stl容器,我不确定它是否可行。
我正在寻找一些方法来使模板结果出现良好的编译错误。 可悲的是,我也不能使用boost,因为平台不支持它。
您基本上有两个解决方案: SFINAE (C ++ 98)或static_assert
(C ++ 11):
您只能为小于给定大小的char数组提供Param
的构造函数。 在C ++ 98中,这看起来有点难看,但它有效:
#include <cstddef>
template<bool b>
struct enable_if {};
template<>
struct enable_if<true>
{
typedef int type;
};
template<std::size_t MAXSIZE>
struct Param
{
template<std::size_t SIZE>
explicit Param(
char const (&input) [SIZE],
std::size_t = sizeof(typename enable_if<SIZE < MAXSIZE>::type) // SFINAE at work
) { (void) input; }
};
int main()
{
// "hello": char const[6], 6 < 7, OK
Param<7> p1("hello");
// "hello world": char const[12], 12 >= 7, KO
Param<7> p2("hello world"); // ugly error here
}
在Param
的构造函数中,您可以检查提供的char数组是否太大并在编译时弹出可读错误:
#include <cstddef>
#include <type_traits>
template<std::size_t MAXSIZE>
struct Param
{
template<std::size_t SIZE>
explicit Param(char const (&input) [SIZE])
{ static_assert(sizeof(input) < MAXSIZE, "input is too big."); }
};
int main()
{
// "hello": char const[6], 6 < 7, OK
Param<7> p1("hello");
// "hello world": char const[12], 12 >= 7, KO
Param<7> p2("hello world"); // "error: static assertion failed: input is too big."
}
也许最简单的方法是添加一个static_assert
,使用一个旧的C技术编译时检查 ,如果你的执行不具有static_assert
尚未:
#include <cstring>
#if __cplusplus < 201103L
#define static_assert(expr, message) \
int static_assert_(int (&static_assert_failed)[(expr)?1:-1])
#endif
template<int N>
struct Param
{
static const int c_max = 10;
static_assert(N < c_max, "Param string too long");
char value[c_max];
Param(char const (&p_value)[N])
{
std::memcpy(value, p_value, sizeof p_value);
}
};
int main()
{
Param okParam("Yeah!"); // this line should be ok
Param nOkParam("REEEEEEEEEEE"); // too big array, not ok. compiler error.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.