Doubleton class - transition from single to double - c++

Below I managed to create a singleton class that allows the instantiation of an object.
How can I modify the code as simple as possible to get a "Doubleton", to have two objects?
#include<iostream>
using namespace std;
class Singleton
{
public:
static Singleton& instance()
{
return uniqueInstance;
}
int getValue() { return data;}
void setValue(int value) { data = value;}
private:
static Singleton uniqueInstance;
int data;
Singleton(int d = 0):data(d) { }
Singleton & operator=(Singleton & ob){
if (this != &ob) data = ob.data; return *this; }
Singleton(const Singleton & ob) { data = ob.data; }
};
Singleton Singleton::uniqueInstance (0);
int main()
{
Singleton& s1 = Singleton::instance();
cout << s1.getValue() << endl;
Singleton& s2 = Singleton::instance();
s2.setValue(9);
cout << s1.getValue() <<endl;
return 0;
}

"Templetize" it:
#include<iostream>
using namespace std;
template<int N>
class Singleton {
public:
static Singleton& instance() {
return uniqueInstance;
}
int getValue() const { return data; }
void setValue(int value) { data = value; }
private:
static Singleton uniqueInstance;
int data;
Singleton(int d = 0) : data(d) {}
Singleton& operator=(Singleton& ob) {
if (this != &ob) data = ob.data;
return *this;
}
Singleton(const Singleton& ob) { data = ob.data; }
};
template<int N>
Singleton<N> Singleton<N>::uniqueInstance(0);
int main() {
Singleton<0>& s1 = Singleton<0>::instance();
cout << s1.getValue() << endl;
Singleton<1>& s2 = Singleton<1>::instance();
s2.setValue(9);
cout << s2.getValue() << endl;
return 0;
}
But to be honest, this is an anti-pattern if you need to do this I'd suggest reviewing the architecture...

Related

Singleton with template [duplicate]

This question already has answers here:
`auto` specifier type deduction for references
(2 answers)
Closed 5 years ago.
#include<iostream>
#include<mutex>
#include<stdlib.h>
using namespace std;
template<typename T>
class Singleton {
public:
static T& getInstance() {
if (instance_ == nullptr){
std::lock_guard<mutex> guard(mutex_);
if (instance_ == nullptr) {
instance_ = new T();
atexit(&Singleton::destroy);
}
}
return *instance_;
}
private:
static void destroy() {
delete instance_;
instance_ = nullptr;
}
Singleton() {}
Singleton(const Singleton&) {}
Singleton& operator=(const Singleton&) {}
static T* instance_;
static mutex mutex_;
};
template<typename T>
T* Singleton<T>::instance_ = nullptr;
template<typename T>
mutex Singleton<T>::mutex_;
class Test {
public:
Test() {
i_ = 0;
cout << "Construct Test" << endl;
}
void setValue(int&& x) {
i_ = x;
}
int getValue() {
return i_;
}
private:
int i_;
};
void main(){
auto instance1 = Singleton<Test>::getInstance();
auto instance2 = Singleton<Test>::getInstance();
instance1.setValue(2);
cout << instance2.getValue() << endl;
cout << instance1.getValue() << endl;
system("pause");
}
Why the type of instance1 and instance2 is Test not Test& ? "Construct Test" print only once, but the result is 0 and 2, instancen1 and instance2 seems two different Test object, the Environment is vs2015
Why the type of instance1 and instance2 is Test not Test& ?
Because you would need to use auto& in place of auto
auto& instance1 = Singleton<Test>::getInstance();
auto& instance2 = Singleton<Test>::getInstance();
You could verify that you're copying instead of getting a reference to the singleton variable with a copy constructor
Test(const Test&) {
cout << "Copying";
}
The rule is
int i = 5;
auto a1 = i; // value
auto & a2 = i; // reference
I'd also pay attention to Baum mit Augen's comment and avoid using void main and stdlib.h in the first place.

Is there a way to have a public member, unmodifiable from outside the class, without accessor wrapper function?

As far as I know, this seems to be impossible in a straightforward way. Making the member const makes it const for everyone. I would like to have a read-only property, but would like to avoid the typical "getter". I'd like const public, mutable private. Is this at all possible in C++?
Currently all I can think of is some trickery with templates and friend. I'm investigating this now.
Might seem like a stupid question, but I have been surprised by answers here before.
A possible solution can be based on an inner class of which the outer one is a friend, like the following one:
struct S {
template<typename T>
class Prop {
friend struct S;
T t;
void operator=(T val) { t = val; }
public:
operator const T &() const { return t; }
};
void f() {
prop = 42;
}
Prop<int> prop;
};
int main() {
S s;
int i = s.prop;
//s.prop = 0;
s.f();
return i, 0;
}
As shown in the example, the class S can modify the property from within its member functions (see S::f). On the other side, the property cannot be modified in any other way but still read by means of the given operator that returns a const reference to the actual variable.
There seems to be another, more obvious solution: use a public const reference member, pointing to the private, mutable, member. live code here.
#include <iostream>
struct S {
private:
int member;
public:
const int& prop;
S() : member{42}, prop{member} {}
S(const S& s) : member{s.member}, prop{member} {}
S(S&& s) : member(s.member), prop{member} {}
S& operator=(const S& s) { member = s.member; return *this; }
S& operator=(S&& s) { member = s.member; return *this; }
void f() { member = 32; }
};
int main() {
using namespace std;
S s;
int i = s.prop;
cout << i << endl;
cout << s.prop << endl;
S s2{s};
// s.prop = 32; // ERROR: does not compile
s.f();
cout << s.prop << endl;
cout << s2.prop << endl;
s2.f();
S s3 = move(s2);
cout << s3.prop << endl;
S s4;
cout << s4.prop << endl;
s4 = s3;
cout << s4.prop << endl;
s4 = S{};
cout << s4.prop << endl;
}
I like #skypjack's answer, but would have written it somehow like this:
#include <iostream>
template <class Parent, class Value> class ROMember {
friend Parent;
Value v_;
inline ROMember(Value const &v) : v_{v} {}
inline ROMember(Value &&v) : v_{std::move(v)} {}
inline Value &operator=(Value const &v) {
v_ = v;
return v_;
}
inline Value &operator=(Value &&v) {
v_ = std::move(v);
return v_;
}
inline operator Value& () & {
return v_;
}
inline operator Value const & () const & {
return v_;
}
inline operator Value&& () && {
return std::move(v_);
}
public:
inline Value const &operator()() const { return v_; }
};
class S {
template <class T> using member_t = ROMember<S, T>;
public:
member_t<int> val = 0;
void f() { val = 1; }
};
int main() {
S s;
std::cout << s.val() << "\n";
s.f();
std::cout << s.val() << "\n";
return 0;
}
Some enable_ifs are missing to really be generic to the core, but the spirit is to make it re-usable and to keep the calls looking like getters.
This is indeed a trickery with friend.
You can use curiously recurring template pattern and friend the super class from within a property class like so:
#include <utility>
#include <cassert>
template<typename Super, typename T>
class property {
friend Super;
protected:
T& operator=(const T& val)
{ value = val; return value; }
T& operator=(T&& val)
{ value = val; return value; }
operator T && () &&
{ return std::move(value); }
public:
operator T const& () const&
{ return value; }
private:
T value;
};
struct wrap {
wrap() {
// Assign OK
prop1 = 5; // This is legal since we are friends
prop2 = 10;
prop3 = 15;
// Move OK
prop2 = std::move(prop1);
assert(prop1 == 5 && prop2 == 5);
// Swap OK
std::swap(prop2, prop3);
assert(prop2 == 15 && prop3 == 5);
}
property<wrap, int> prop1;
property<wrap, int> prop2;
property<wrap, int> prop3;
};
int foo() {
wrap w{};
w.prop1 = 5; // This is illegal since operator= is protected
return w.prop1; // But this is perfectly legal
}

Forcing class instances to be const

Is there any way to force to only allow const instances of class to be instantiated, and have non-const instances be detected as an error by the compiler?
is there any generic way to take an existing class, and "constify" it by removing all non-const functionality?
One possible workaround is to create a wrapper class that holds an instance of the class and only gives access to a const reference to it.
template<class T>
class Immutable {
public:
template<typename... Args>
Immutable(Args&&... args) : instance(forward<Args>(args)...) {
}
operator const T&() {
return instance;
}
const T& get() const {
return instance;
}
private:
Immutable& operator=(const Immutable& other) = delete;
T instance;
};
Suppose you have a mutable class Class:
class Class {
public:
Class() : m_value(0) {
}
Class(const Class& other) : m_value(other.m_value) {
}
Class(int value) : m_value(value) {
}
Class(int x, int y) : m_value(x + y) {
}
void change(int value) {
m_value = value;
}
int value() const {
return m_value;
}
private:
int m_value;
};
Here is how Immutable<Class> can be used:
void functionTakingConstReference(const Class& x) {
}
void functionTakingNonConstReference(Class& x) {
}
void functionTakingImmutableClass(Immutable<Class>& x) {
}
void functionTakingValue(Class x) {
}
int main(int argc, char *argv[])
{
// Any constructor of Class can also be used with Immutable<Class>.
Immutable<Class> a;
Immutable<Class> b(1);
Immutable<Class> c(2, 3);
Immutable<Class> d(c);
// Compiles and works as expected.
functionTakingConstReference(a);
functionTakingImmutableClass(a);
functionTakingValue(a);
cout << a.get().value() << endl;
// Doesn't compile because operator= is deleted.
// b = a;
// Doesn't compile because "change" is a non-const method.
// a.get().change(4);
// Doesn't compile because the function takes a non-const reference to Class as an argument.
// functionTakingNonConstReference(a);
return 0;
}
Is there any way to force to only allow const instances of class to be instantiated, and have non-const instances be detected as an error by the compiler?
No.
But you can declare all members as const. Then both const and non-const instances would behave largely in the same way and it shouldn't matter whether the instances are const.
I think you are looking for an immutable class. An easy way to get immutability is to declare all member variables as const. This way you ensure that the state of your objects will not change after construction.
This guarantee is independent of whether your object is const and even if you have non-const member functions for that class.
For example:
class Foo
{
public:
Foo(int id, double value) : m_id(id), m_value(value) { }
int Id() const { return m_id; }
double Value() const { return m_value; }
private:
const int m_id;
const double m_value;
};
Another way you could generate an immutable object of any type is through a template class. Something like this:
class Bar
{
public:
Bar(int id, double value) : m_id(id), m_value(value) { }
int Id() const { return m_id; }
double Value() const { return m_value; }
void SetId(int id) { m_id = id; }
private:
int m_id;
double m_value;
};
template<typename T>
class MyImmutable
{
public:
const T m_obj;
MyImmutable(const T& obj) : m_obj(obj)
{ }
};
int main()
{
cout << "Hello World!" << endl;
Foo a(1,2.0);
Bar x(2,3.0);
MyImmutable<Bar> y(x);
cout << "a.id = " << a.Id() << endl;
cout << "a.value = " << a.Value() << endl;
cout << "y.id = " << y.m_obj.Id() << endl;
cout << "y.value = " << y.m_obj.Value() << endl;
y.m_obj.SetId(2); // calling non-const member throws an error.
return 0;
}

c++ runtime instantiation of member parameter

As the title says I would like to initiate a Store object whose type is determined at runtime only. I initially went for a virtual class, 2 derived classes but quickly faced the need for templates.
The class O has a pointer to an interface BaseStore for these Store objects. Moreover since I also need to call the right functions for the Derived classes Store1 and Store2, I used a dynamic cast in a template function of the interface.
Since I am new to c++, I wonder if this design has flaws and if there is any place for improvements. Thanks for your expertise!
#include <iostream>
using namespace std;
struct BaseStore {
virtual ~BaseStore() {}
template<typename S> void test() const;
};
struct Store1 : public BaseStore {
Store1(int j) { this->i = j; }
void test() const { cout << i << endl; }
private:
int i = 1;
};
struct Store2 : public BaseStore {
Store2(string s) { this->i = s; }
void test() const { cout << i << endl; }
private:
string i = "2";
};
template<typename S> void BaseStore::test() const
{
dynamic_cast<const S&>(*this).test();
}
class O {
public:
O(int i) {
this->type = i;
switch (this->type) {
case 1: basestore = new Store1(42); break;
case 2: basestore = new Store2("lol"); break;
}
}
~O() { delete basestore; }
void test() const {
switch (this->type) {
case 1: basestore->test<Store1>(); break;
case 2: basestore->test<Store2>(); break;
}
}
private:
int type;
BaseStore* basestore;
};
I believe virtual functions and the factory pattern will help here, as in:
struct BaseStore
{
virtual ~BaseStore() = default;
virtual void test() const = 0;
BaseStore() = default;
BaseStore(BaseStore const&) = delete;
BaseStore(BaseStore&&) = delete;
BaseStore& operator=(BaseStore&&) = delete;
BaseStore& operator=(BaseStore const&) = delete;
};
struct Store1 : public BaseStore {
Store1(int j) : i(j) {}
void test() const override { std::cout << i << std::endl; }
private:
int i = 1;
};
struct Store2 : public BaseStore {
Store2(std::string s) : i(std::move(s)) {}
void test() const override { std::cout << i << std::endl; }
private:
std::string i = "2";
};
class O {
public:
O(int i) : type(i), basestore(StoreFactory(i)) {}
void test() const { basestore->test(); }
private:
static std::unique_ptr<BaseStore> StoreFactory(int i)
{
switch (i)
{
case 1: return std::unique_ptr<Store1>(new Store1(42));
case 2: return std::unique_ptr<Store2>(new Store2("lol"));
default: throw std::runtime_error("Don't know what kind of Store you want");
}
}
int type;
std::unique_ptr<BaseStore> basestore;
};

Property like features in C++?

My use is pretty complicated. I have a bunch of objs and they are all passed around by ptr (not reference or value unless its an enum which is byval). At a specific point in time i like to call CheckMembers() which will check if each member has been set or is null. By default i cant make it all null because i wouldnt know if i set it to null or if it is still null bc i havent touch it since the ctor.
To assign a variable i still need the syntax to be the normal var = p; var->member = new Type;. I generate all the classes/members. So my question is how can i implement a property like feature where i can detect if the value has been set or left as the default?
I am thinking maybe i can use C++ with CLR/.NET http://msdn.microsoft.com/en-us/library/z974bes2.aspx but i never used it before and have no idea how well it will work and what might break in my C++ prj (it uses rtti, templates, etc).
Reality (edit): this proved to be tricky, but the following code should handle your requirements. It uses a simple counter in the base class. The counter is incremented once for every property you wish to track, and then decremented once for every property that is set. The checkMembers() function only has to verify that the counter is equal to zero. As a bonus, you could potentially report how many members were not initialized.
#include <iostream>
using namespace std;
class PropertyBase
{
public:
int * counter;
bool is_set;
};
template <typename T>
class Property : public PropertyBase
{
public:
T* ptr;
T* operator=(T* src)
{
ptr = src;
if (!is_set) { (*counter)--; is_set = true; }
return ptr;
}
T* operator->() { return ptr; }
~Property() { delete ptr; }
};
class Base
{
private:
int counter;
protected:
void TrackProperty(PropertyBase& p)
{
p.counter = &counter;
counter++;
}
public:
bool checkMembers() { return (counter == 0); }
};
class OtherObject : public Base { }; // just as an example
class MyObject : public Base
{
public:
Property<OtherObject> x;
Property<OtherObject> y;
MyObject();
};
MyObject::MyObject()
{
TrackProperty(x);
TrackProperty(y);
}
int main(int argc, char * argv[])
{
MyObject * object1 = new MyObject();
MyObject * object2 = new MyObject();
object1->x = new OtherObject();
object1->y = new OtherObject();
cout << object1->checkMembers() << endl; // true
cout << object2->checkMembers() << endl; // false
delete object1;
delete object2;
return 0;
}
There are a number of ways to do this, with varying tradeoffs in terms of space overhead. For example, here's one option:
#include <iostream>
template<typename T, typename OuterClass>
class Property
{
public:
typedef void (OuterClass::*setter)(const T &value);
typedef T &value_type;
typedef const T &const_type;
private:
setter set_;
T &ref_;
OuterClass *parent_;
public:
operator value_type() { return ref_; }
operator const_type() const { return ref_; }
Property<T, OuterClass> &operator=(const T &value)
{
(parent_->*set_)(value);
return *this;
}
Property(T &ref, OuterClass *parent, setter setfunc)
: set_(setfunc), ref_(ref), parent_(parent)
{ }
};
struct demo {
private:
int val_p;
void set_val(const int &newval) {
std::cout << "New value: " << newval << std::endl;
val_p = newval;
}
public:
Property<int, demo> val;
demo()
: val(val_p, this, &demo::set_val)
{ }
};
int main() {
demo d;
d.val = 42;
std::cout << "Value is: " << d.val << std::endl;
return 0;
}
It's possible to get less overhead (this has up to 4 * sizeof(void*) bytes overhead) using template accessors - here's another example:
#include <iostream>
template<typename T, typename ParentType, typename AccessTraits>
class Property
{
private:
ParentType *get_parent()
{
return (ParentType *)((char *)this - AccessTraits::get_offset());
}
public:
operator T &() { return AccessTraits::get(get_parent()); }
operator T() { return AccessTraits::get(get_parent()); }
operator const T &() { return AccessTraits::get(get_parent()); }
Property &operator =(const T &value) {
AccessTraits::set(get_parent(), value);
return *this;
}
};
#define DECL_PROPERTY(ClassName, ValueType, MemberName, TraitsName) \
struct MemberName##__Detail : public TraitsName { \
static ptrdiff_t get_offset() { return offsetof(ClassName, MemberName); }; \
}; \
Property<ValueType, ClassName, MemberName##__Detail> MemberName;
struct demo {
private:
int val_;
struct AccessTraits {
static int get(demo *parent) {
return parent->val_;
}
static void set(demo *parent, int newval) {
std::cout << "New value: " << newval << std::endl;
parent->val_ = newval;
}
};
public:
DECL_PROPERTY(demo, int, val, AccessTraits)
demo()
{ val_ = 0; }
};
int main() {
demo d;
d.val = 42;
std::cout << "Value is: " << (int)d.val << std::endl;
return 0;
}
This only consumes one byte for the property struct itself; however, it relies on unportable offsetof() behavior (you're not technically allowed to use it on non-POD structures). For a more portable approach, you could stash just the this pointer of the parent class in a member variable.
Note that both classes are just barely enough to demonstrate the technique - you'll want to overload operator* and operator->, etc, as well.
Here's my temporary alternative. One that doesn't ask for constructor parameters.
#include <iostream>
#include <cassert>
using namespace std;
template <class T>
class Property
{
bool isSet;
T v;
Property(Property&p) { }
public:
Property() { isSet=0; }
T operator=(T src) { v = src; isSet = 1; return v; }
operator T() const { assert(isSet); return v; }
bool is_set() { return isSet; }
};
class SomeType {};
enum SomeType2 { none, a, b};
class MyObject
{
public:
Property<SomeType*> x;
Property<SomeType2> y;
//This should be generated. //Consider generating ((T)x)->checkMembers() when type is a pointer
bool checkMembers() { return x.is_set() && y.is_set(); }
};
int main(int argc, char * argv[])
{
MyObject* p = new MyObject();
p->x = new SomeType;
cout << p->checkMembers() << endl; // false
p->y = a;
cout << p->checkMembers() << endl; // true
delete p->x;
delete p;
}