not_null and maybe_null variants should only work on pointer types.

This commit is contained in:
Kern Handa 2015-09-25 09:41:40 -07:00
parent 8ae77b1fd5
commit 40009ff6eb
3 changed files with 10 additions and 0 deletions

View File

@ -102,6 +102,7 @@ typename Cont::value_type& at(Cont& cont, size_t index) { fail_fast_assert(index
template<class T> template<class T>
class not_null class not_null
{ {
static_assert(std::is_pointer<T>::value, "T must be a pointer type");
public: public:
not_null(T t) : ptr_(t) { ensure_invariant(); } not_null(T t) : ptr_(t) { ensure_invariant(); }
@ -162,6 +163,7 @@ private:
template<class T> template<class T>
class maybe_null_dbg class maybe_null_dbg
{ {
static_assert(std::is_pointer<T>::value, "T must be a pointer type");
public: public:
maybe_null_dbg() : ptr_(nullptr), tested_(false) {} maybe_null_dbg() : ptr_(nullptr), tested_(false) {}
@ -237,6 +239,7 @@ private:
template<class T> template<class T>
class maybe_null_ret class maybe_null_ret
{ {
static_assert(std::is_pointer<T>::value, "T must be a pointer type");
public: public:
maybe_null_ret() : ptr_(nullptr) {} maybe_null_ret() : ptr_(nullptr) {}
maybe_null_ret(std::nullptr_t) : ptr_(nullptr) {} maybe_null_ret(std::nullptr_t) : ptr_(nullptr) {}

View File

@ -16,6 +16,7 @@
#include <UnitTest++/UnitTest++.h> #include <UnitTest++/UnitTest++.h>
#include <gsl.h> #include <gsl.h>
#include <vector>
using namespace Guide; using namespace Guide;
@ -27,6 +28,10 @@ SUITE(MaybeNullTests)
{ {
TEST(TestMaybeNull1) TEST(TestMaybeNull1)
{ {
#ifdef CONFIRM_COMPILATION_ERRORS
maybe_null_dbg<std::vector<int>> f(std::vector<int>{1}); // Not a pointer type. Must be tested with a non-integral type.
maybe_null_ret<std::vector<int>> g(std::vector<int>{1}); // Not a pointer type. Must be tested with a non-integral type.
#endif
int n = 5; int n = 5;
maybe_null_dbg<int *> opt_n(&n); maybe_null_dbg<int *> opt_n(&n);
int result = 0; int result = 0;

View File

@ -16,6 +16,7 @@
#include <UnitTest++/UnitTest++.h> #include <UnitTest++/UnitTest++.h>
#include <gsl.h> #include <gsl.h>
#include <vector>
using namespace Guide; using namespace Guide;
@ -48,6 +49,7 @@ SUITE(NotNullTests)
not_null<int*> p; // yay...does not compile! not_null<int*> p; // yay...does not compile!
std::unique_ptr<int> up = std::make_unique<int>(120); std::unique_ptr<int> up = std::make_unique<int>(120);
not_null<int*> p = up; not_null<int*> p = up;
not_null<std::vector<int>> f(std::vector<int>{1}); // Not a pointer type. Must be tested with a non-integral type.
#endif #endif
int i = 12; int i = 12;
auto rp = RefCounted<int>(&i); auto rp = RefCounted<int>(&i);