c++ - Validation of Iterator -


i working in c++03 project. , i'm taking iterator template. need assert iterator references specific type. does c++ provide me way beyond writing own struct validation?

what want equivalent of c++14 functionality:

static_assert(is_same<iterator_traits<inputiterator>::value_type, int>(), "not int iterator"); 

since it's c++03 assume i'll have use assert , that's fine if it's runtime debug check need check there.

c++03 doesn't come static_assert-type thing, that's c++11 feature. however, there's boost_static_assert. if boost not available you, straightforward thing write:

namespace detail {     template <bool > struct my_static_assert;     template <> struct my_static_assert<true> { };      template <size_t > struct my_tester { }; }  #define my_static_assert(b) \     typedef ::detail::my_tester< sizeof(::detail::my_static_assert< ((b) == 0 ? false : true) >)> \         my_static_assert_typedef_ ## __counter__ __attribute__((unused)) 

the idea that, take our expression b, convert bool, , use in context if it's true, we'll have complete type, , if it's false, won't. cannot take sizeof() incomplete type, that'll compile error.

so if did:

my_static_assert(sizeof(int) >= 5); 

gcc gives me:

main.cpp: in function 'int main()': main.cpp:9:92: error: invalid application of 'sizeof' incomplete type 'detail::my_static_assert<false>'      typedef detail::my_tester< sizeof(detail::my_static_assert< ((b) == 0 ? false : true) >)> \                                                                                             ^ main.cpp:15:5: note: in expansion of macro 'my_static_assert'      my_static_assert(sizeof(int) >= 5);       ^ 

it's not quite nice as:

main.cpp:15:5: error: static assertion failed:       static_assert(sizeof(int) >= 5, "");       ^ 

but then, that's happens when don't have language feature.


with that, can convert:

static_assert(std::is_same<std::iterator_traits<inputiterator>::value_type, int>(),               "not int iterator"); 

to:

namespace details {     template <typename t, typename u>     struct is_same { static const bool value = false; };      template <typename t>     struct is_same<t, t> { static const bool value = true; }; }  my_static_assert(details::is_same<     std::iterator_traits<inputiterator>::value_type, int     >::value); // not int iterator 

iterator_traits existed in c++03, , adding comment let message show in compile error.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -