我正在一个C++03项目中工作。我把一个迭代器放到一个模板里。我需要断言这个迭代器引用了一个特定的类型。 C++提供了一种方法来完成这一任务,而不仅仅是为验证编写自己的结构吗?
我想要的是相当于这个C++14功能的功能:
static_assert(is_same<iterator_traits<InputIterator>::value_type, int>(), "Not an int iterator");因为它是C++03,所以我假设我必须使用一个assert,如果它只是一个运行时调试检查,那就好了,我只需要检查就可以了。
发布于 2015-08-05 14:05:49
由于问题的参数如下:
除了编写我自己的结构以进行验证之外,还可以这样做。
并假定:
我将不得不使用
assert,如果它只是运行时调试检查,那就好了。
您可以在typeid中使用C++03:
assert(typeid(iterator_traits<InputIterator>::value_type) == typeid(int));发布于 2015-08-05 13:39:26
C++03没有提供static_assert-type功能,这是一个C++11特性。然而,有BOOST_STATIC_ASSERT。如果Boost对您来说是不可用的,那么这实际上是一件相当简单的事情:
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))我们的想法是,我们将表达式B转换为bool,并在上下文中使用它--如果它是true,我们将有一个完整的类型,如果是false,则不会。不能将sizeof()作为一个不完整的类型,所以这将是一个编译错误。
所以如果我这么做了
MY_STATIC_ASSERT(sizeof(int) >= 5);gcc告诉我:
main.cpp: In function 'int main()':
main.cpp:9:92: error: invalid application of 'sizeof' to 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);
^它不像:
main.cpp:15:5: error: static assertion failed:
static_assert(sizeof(int) >= 5, "");
^但是,当你没有语言特性时,就会发生这种情况。
这样,我们就可以转换:
static_assert(std::is_same<std::iterator_traits<InputIterator>::value_type, int>(),
"Not an int iterator");至:
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 an int iteratoriterator_traits已经存在于C++03中,添加注释将使消息显示在编译错误中。
https://stackoverflow.com/questions/31833617
复制相似问题