|
Boost : |
From: Johan Paulsson (boost.list_at_[hidden])
Date: 2005-03-15 07:09:20
(If this is off topic, has already been discussed, or is stupid, I'm sorry)
I wanted a static assert without #define, I ended up with this:
template<bool MustBeTrue, int TemplateAssertError = 1 /
static_cast<int>(MustBeTrue)>
class template_assert {};
so
template_assert<true> means TemplateAssertError = 1 / 1, no error
template_assert<false> means TemplateAssertError = 1 / 0, error
The only compiler I have is MSVC++ 2003. I have no idea how other
compilers like it, but to me this seems like a better alternative to
BOOST_STATIC_ASSERT. Is it?
An example, with the code that will trigger template_assert commented out:
//
template<class Type>
struct test {
typedef template_assert<sizeof(Type) == sizeof(int)> assert_type;
void do_nothing() {}
};
template<bool Boo>
void function() {
template_assert<Boo>();
test<int> works;
works.do_nothing();
//test<char> fails;
//fails.do_nothing();
}
void start() {
function<true>(); //works
//function<false>(); //fails
}
//
In MSVC++ 2003 i can also use:
template<bool Boo>
void function() {
template_assert<Boo>; //<-- no parenthesis
...
but i suppose this is not portable (I don't have a copy of the C++
standard).
Thank you all for making boost!
/Johan Paulsson
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk