Skip to content

Instantly share code, notes, and snippets.

@vietjtnguyen
Last active January 13, 2021 19:01
Show Gist options
  • Save vietjtnguyen/0ef09550e911453b836dc139bc9b565c to your computer and use it in GitHub Desktop.
Save vietjtnguyen/0ef09550e911453b836dc139bc9b565c to your computer and use it in GitHub Desktop.
Throw/assert method as customization point?
#pragma once
#ifdef MY_LIB_THROW_INSTEAD_OF_ASSERT
#include <stdexcept>
#define MY_LIB_ASSERT(condition) \
if (not condition) throw std::runtime_error(#condition)
#endif
#ifndef MY_LIB_ASSERT
#include <cassert>
#define MY_LIB_ASSERT(condition) (assert(condition))
#endif
#include "foo.hpp"
#include "assert.hpp"
namespace my_lib {
foo::foo(int x)
: x_(x)
{
MY_LIB_ASSERT(x != 0);
}
int
foo::get_x() const
{
return this->x_;
}
}
#pragma once
namespace my_lib {
class foo {
public:
foo(int x);
int get_x() const;
private:
int x_;
};
}
#include "foo.hpp"
int main()
{
my_lib::foo x(0);
if (x.get_x() == 0) {
return -1;
}
return 0;
}
.PHONY: all
all: foo_with_assert foo_with_throw
foo_with_assert: assert.hpp foo.hpp foo.cpp main.cpp
g++ -std=c++11 -o foo_with_assert main.cpp foo.cpp -g -O0
foo_with_throw: assert.hpp foo.hpp foo.cpp main.cpp
g++ -std=c++11 -o foo_with_throw main.cpp foo.cpp -g -O0 -
DMY_LIB_THROW_INSTEAD_OF_ASSERT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment