From: Douglas Gregor (gregod_at_[hidden])
Date: 2002-02-17 18:46:52
On Sunday 17 February 2002 02:22 am, you wrote:
> I'm not sure it's possible, but a nice addition to Boost would be the
> ability to determine if an expression is a constant integer or not.
> Everything I've thought of would cause an error if the expression were
> not a constant.
> I can imagine a couple of uses for this, but the immediate need is to
> not allow the following to compile:
> char buf;
> strncpy(buf, "this will overrun", 512); // oops, 512 >
> Here, the compiler can deduce the array bounds. If the count expression
> is constant, then it's simple to cause a compile time error. If it's
> not, then no error should happen.
> Of course tools such as the compiler can be taught to catch this, but a
> pure language implementation would be really cool.
> Jason Shirk
> VC++ Compiler Team
This would be great, indeed, but it would seem impossible in the current
language. Values that occur within the run-time part of the language (e.g.,
the function call above) don't seem to have any way to migrate into the
compile-time part of the language (e.g., something like strncpy<512>(buf,
"this will overrun") would do what you want). I'd be overjoyed to see
something prove me wrong on this :)
Aleksey has a solution to this that requires only a small language extension,
which he mentions here:
With this extension, one could add a strncpy() overload that looks like this:
template<int N, int M>
inline void strncpy(char buf[N], const char* s, M)
BOOST_STATIC_ASSERT(N > M);
int M = m;
strncpy(buf, s, m);
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk