Skip to content

Instantly share code, notes, and snippets.

@mjschutz
Created October 29, 2015 17:19
Show Gist options
  • Save mjschutz/fc29eaf42ca9e08f11bb to your computer and use it in GitHub Desktop.
Save mjschutz/fc29eaf42ca9e08f11bb to your computer and use it in GitHub Desktop.
Class to manipulate type or pointer type as a non-pointer value without using std::remove_reference with release if pointer type
template <typename Tp>
struct NoPtrType {
typedef Tp noref_type;
static inline Tp read(Tp value) { return value; }
static inline Tp write(Tp& value, noref_type const& in_value) { value = in_value; return in_value; }
static inline void release_if_pointer(Tp const&) {}
};
template <typename Tp>
struct NoPtrType<Tp*> {
typedef Tp noref_type;
static inline Tp read(Tp* value) { return *value; }
static inline Tp write(Tp* value, noref_type const& in_value) { *value = in_value; return in_value; }
static inline void release_if_pointer(Tp* const& value) { if (value != nullptr) delete value; }
};
template <typename Tp>
class Value
{
Tp value;
public:
typedef typename NoPtrType<Tp>::noref_type type;
Value(Tp ivalue): value(ivalue) {}
virtual ~Value() { NoPtrType<Tp>::release_if_pointer(value); }
type operator=(type const& val)
{
return NoPtrType<Tp>::write(value, val);
}
operator type()
{
return NoPtrType<Tp>::read(value);
}
};
#include <iostream>
int main()
{
Value<int*> value(new int(5));
Value<int> value2(5);
value = 10;
std::cout << "value: " << value << std::endl << "value2 " << value2 << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment