Convert enum values from external library to local datatypes - c++11

I have lot of enum from external library, which I am trying to convert it to local datatypes. I do not want datatypes or header files from external library to be included everywhere in the client code.
At present I am doing something like below. Is there a better way to do this.
struct ExtServer {
enum class Color { RED, BLACK, GREEN, ORANGE };
enum class Fruit { ORANGE, APPLE };
};
struct Wrapper {
enum class Color { RED, BLACK, GREEN, ORANGE };
enum class Fruit { ORANGE, APPLE };
template<typename T, typename U>
T convert(U value) { return static_cast<T>(value); }
Color From(ExtServer::Color color) {
return convert<Color, decltype(color)>(color);
}
Fruit From(ExtServer::Fruit fruit) {
return convert<Fruit, decltype(fruit)>(fruit);
}
};
struct Client {
void do_something() {
Wrapper obj;
obj.From(ExtServer::Color::RED);
obj.From(ExtServer::Fruit::APPLE);
}
};
int main() {
Client client;
client.do_something();
}

Related

Can i use 2 different functions returning different data types inside my template function code?

I am trying to templatize some of my code and am not sure if i am doing it correct way ?
template <typename T>
class User
{
public:
template <typename T>
void foo() {
A* pa = funcA();
OR
B* pb = funcB();
//common code follows
....
....
....
};
User<Atype> C1;
User<Btype> C2;
In the above code I am looking as to how to define foo() as to be able to use
either of A* pa = funcA() or B* pb = funcB() based on how the class is instantiated. C1 should be able to use A* pa = funcA() and C2 should be able to use B* pb = funcB().
Not directly, but there is various options. Normally it is best to avoid designs that result in needing different named functions, or conceptually different operations.
For example if both A and B had a member or static function foo, then you could call that (x.foo(), T::foo(), etc.) instead of having the separately named funcA and funcB. Or similarly, in the case of parameters you can use function overloading (as you can't overload on the return type), such as std::to_string, and sometimes using templates as well such as std::swap.
Otherwise, if you need to support completely different things, then there are many options.
You can specialise foo to have different implementations for different types. This is often not particularly ideal if you are planning to use many different types with a template function or class. In some cases you might specialise the entire class, and there is also partial specialisation.
class A {};
class B {};
A *funcA();
B *funcB();
template <typename T>
class User
{
public:
void foo();
};
template<> void User<A>::foo()
{
auto a = funcA();
// ...
}
template<> void User<B>::foo()
{
auto ab = funcB();
// ...
}
Similar to 1, you can have a separate template function or class that is specialised.
class A {};
class B {};
A *funcA();
B *funcB();
template<class T> T *funcGeneric();
template<> A *funcGeneric<A>() { return funcA(); }
template<> B *funcGeneric<B>() { return funcB(); }
template <typename T>
class User
{
public:
void foo()
{
auto p = funcGeneric<T>();
}
};
Or with a class, which can be useful if you have multiple methods or pieces of information. For a single method, the call operator is often overloaded.
template<class T> class FuncGeneric;
template<> class FuncGeneric<A>
{
public:
A *operator()()const { return funcA(); }
};
template<> class FuncGeneric<B>
{
public:
B *operator()()const { return funcB(); }
};
template <typename T>
class User
{
public:
void foo()
{
auto p = FuncGeneric<T>()();
}
};
Extending on 2, but you pass the "adapter" as a template parameter itself. This is one you see in the STL a fair bit, with things like std::map taking the Compare parameter (default std::less), unique_ptr taking a deleter (with std::default_delete calling delete), hash functions, etc.
template<class T> class FuncGeneric;
template<> class FuncGeneric<A>
{
public:
A *operator()()const { return funcA(); }
};
template<> class FuncGeneric<B>
{
public:
B *operator()()const { return funcB(); }
};
template <class T, class Func = FuncGeneric<T>>
class User
{
public:
void foo()
{
auto p = Func()();
}
};
In some cases you might pass the function itself. More common for functions rather than classes, for example many of the algorithms (e.g. find_if) do this.
template <class T, class Func>
class User
{
public:
User(Func func) : func(func) {}
void foo()
{
auto p = func();
}
private:
Func func;
};
int main()
{
User<A, A*(*)()> user(&funcA);
}
Functions can also be a template parameter themselves, although this is fairly uncommon.
template <class T, T*(*Func)()>
class User
{
public:
void foo()
{
auto p = Func();
}
};
int main()
{
User<A, &funcA> user;
}

How to get a reference to the negation of a bool?

For example, if I have a bool value v, I want a reference to !v that can change when v changes. An example use will be:
class A {
bool& isOpen;
A(bool& value): isOpen(value) {}
void f() {
if (isOpen) {
doSomething();
}
}
};
class B {
bool& isClosed;
B(bool& value): isClosed(value) {}
void g() {
if (isClosed) {
doSomething();
}
}
};
int main() {
bool isOpen = true;
A a(isOpen);
B b(negattive_reference_of(isOpen));
a.f(); // doSomething()
b.g(); // do nothing
isOpen = false;
a.f(); // do nothing
b.g(); // doSomething()
}
Is there anyway in C++ to acheive a similar effect?
Under the hood reference is equivalent to a constant pointer to some variable (compiler just gives you a syntax sugar of how to work with such pointers so that they are always initialized).
So you wan't to have the same variable and two different pointers to it, one of which will dereference to true and the other to false. That is obviously impossible.
The OOP -way to do it would be to pass not reference to boolean but some interface to your classes and use implementation that uses same boolean variable:
class IIsOpenProvider
{
public:
virtual ~IIsOpenProvider() = 0;
virtual bool GetOpenValue() = 0;
};
class IIsClosedProvider
{
public:
virtual ~IIsClosedProvider() = 0;
virtual bool GetClosedValue() = 0;
};
class ValueProvider : public IIsOpenProvider, public IIsClosedProvider
{
public:
bool GetOpenValue() override { return isOpen; }
bool GetClosedValue() override { return !isOpen; }
private:
bool isOpen;
};
class A {
IIsOpenProvider& isOpen;
A(IIsOpenProvider& value): isOpen(value) {}
void f() {
if (isOpen.GetOpenValue()) {
doSomething();
}
}
};
class B {
IIsClosedProvider& isClosed;
B(IIsClosedProvider& value): isClosed(value) {}
void g() {
if (IIsClosedProvider.GetClosedValue()) {
doSomething();
}
}
};
// usage
ValueProvider val;
A a(val);
B b(val);

I am trying to use boost, C++ with templates, and factory pattern but can't seem to figure out the right syntax for it?

Here is the specifics:
Consider a simple constructor in a class with two input arguments,
concreteclass(_1, _2).
I have a map for this instantiation, map <string, concreteclassType>.
Also, these classes work with different datatypes concreteclass<double>(_1,_2) is different from concreteclass<int>(_1,_2).
Now that my problem is described above here is what I try to do using boost::factory pattern, classes defined in a string map and datatypes defined in an enum.
First, there is a simple way to demonstrate how boost factory pattern can be used with constructor arguments, the following nicely code works:
// Factory which takes two arguments
struct base {
base(int alpha) : alpha(alpha) {}
virtual ~base() = default;
virtual void print() const = 0;
int alpha;
};
struct derived : public base {
derived(int alpha, int beta) : base(alpha), beta(beta) {}
void print() const override {
std::cout << alpha << " " << beta << std::endl;
}
int beta;
};
void TestBoostFactoryWithTwoArgs()
{
// Constructor factory with two input args
{
std::map<std::string, boost::function<base* (int&, int&)>> factories;
factories["derived"] = boost::bind(boost::factory<derived*>(), _1, _2);
int x = 42;
int y = 51;
std::unique_ptr<base> b{ factories.at("derived")(x,y) };
b->print();
}
// Factory with two initialized inputs args - binding of values not at run time
{
std::map<std::string, boost::function<base* ()>> factories;
factories["derived"] = boost::bind(boost::factory<derived*>(), 42, 51);
std::unique_ptr<base> b{ factories.at("derived")() };
b->print();
}
}
Now consider my code - SimpleClasses.h:
// Dummy base class - non template
class IBaseClass
{
public:
};
// Templatized Derived Base class
template <typename T>
class ConcreteClass : public IBaseClass
{
private:
std::shared_ptr<IBaseClass> m_leftArgument;
std::shared_ptr<IBaseClass> m_leftArgument;
public:
ConcreteClass(std::unique_ptr<IBaseClass>& leftArgument, std::unique_ptr<IBaseClass>& rightArgument)
{
m_leftArgument = leftArgument;
m_rightArgument = rightArgument;
};
virtual T DoSomething()
{
cout << "I did something in Concrete Base Class" << endl;
return T();
}; // This is the main reason for creating T
};
template <typename T>
class ConcreteClassA : ConcreteClass
{
};
template <typename T>
class ConcreteClassB : ConcreteClass
{
};
template <typename T>
class ConcreteClassC : ConcreteClass
{
};
Another File, ClassFactory.h :
#pragma once
#include "SimpleClasses.h"
#include <memory>
#include <map>
#include <boost/functional/overloaded_function.hpp>
#include <boost/functional/factory.hpp>
using namespace std;
// Add More class Keys here
namespace MyClassesNamespace { // These are all string keys
static const string CLASS_A = "specialclassA";
static const string CLASS_B = "specialclassB";
static const string CLASS_C = "specialclassC";
};
enum EMyDataTypes
{
INT8,
FLOAT8,
FLOAT16,
};
// This type def we keep for non templatized base class constructor
typedef boost::function<IBaseClass*(std::unique_ptr<IBaseClass>&, std::unique_ptr<IBaseClass>&)> IBaseClassConstructorFunc_factory;
// Dummy base factory - no template
class UBaseClassTemplateFactory
{
public:
};
template<typename T>
class UClassFactoryTemplate : public UBaseClassTemplateFactory
{
private:
static std::map<string, IBaseClassConstructorFunc_factory> ClassFactoryTemplateMap; // Unique Classes only
public:
UClassFactoryTemplate();
__forceinline static UClassFactoryTemplate*Get()
{
static UClassFactoryTemplate<T> SingletonInstance;
return &SingletonInstance;
}
static std::unique_ptr<IBaseClass<T>> CreateClassTemplatized(string ClassString, std::unique_ptr<IBaseClass> LeftArgument, std::unique_ptr<IBaseClass> RightArgument);
};
// This type def we keep for non templatized base class
typedef boost::function<UBaseClassTemplateFactory*()> ClassFactoryTemplate_factory;
/* This is the instance class that resolves the classes as well as the concrete datatype to be used in UClassFactoryTemplate*/
class UClassFactory
{
private:
UClassFactory();
static std::map<EMyDataTypes, ClassFactoryTemplate_factory> ClassDataTypeTemplateFactoryMap;
public:
__forceinline static UClassFactory *Get()
{
static UClassFactory SingletonInstance;
return &SingletonInstance;
}
static std::unique_ptr<IBaseClass> CreateConcreteClass(string ClassString, std::unique_ptr<IBaseClass> LeftVal, std::unique_ptr<IBaseClass> RightVal, EMyDataTypes someEnumVal = EMyDataTypes::INT8);
};
Finally, in ClassFactory.cpp
#include "ClassFactory.h"
#include <boost/bind.hpp>
/*static, but non-const data members should be defined outside of the class definition
*and inside the namespace enclosing the class. The usual practice is to define it in
*the translation unit (*.cpp) because it is considered to be an implementation detail.
*Only static and const integral types can be declared and defined at the same time (inside class definition):*/
template<typename T>
std::map<string, IBaseClassConstructorFunc_factory> UClassFactoryTemplate<T>::ClassFactoryTemplateMap;
std::map<EMyDataTypes, ClassFactoryTemplate_factory> UClassFactory::ClassDataTypeTemplateFactoryMap;
template<typename T>
inline UClassFactoryTemplate<T>::UClassFactoryTemplate()
{
ClassFactoryTemplateMap[MyClassesNamespace::CLASS_A] = boost::bind(boost::factory<ConcreteClassA<T>*>(), _1, _2);
ClassFactoryTemplateMap[MyClassesNamespace::CLASS_B] = boost::bind(boost::factory<ConcreteClassB<T>*>(), _1, _2);
ClassFactoryTemplateMap[MyClassesNamespace::CLASS_C] = boost::bind(boost::factory<ConcreteClassC<T>*>(), _1, _2);
}
template<typename T>
std::unique_ptr<IBaseClass<T>> UClassFactoryTemplate<T>::CreateClassTemplatized(string ClassString, std::unique_ptr<IBaseClass> LeftArgument, std::unique_ptr<IBaseClass> RightArgument)
{
std::unique_ptr<IBaseClass<T>> someTemplatizedDataTypeInstance{ ClassFactoryTemplateMap.at(ClassString) (LeftArgument,RightArgument) };
return someTemplatizedDataTypeInstance;
}
UClassFactory::UClassFactory()
{
ClassDataTypeTemplateFactoryMap[EMyDataTypes::INT8] = boost::bind(boost::factory<UClassFactoryTemplate<int>*>());
ClassDataTypeTemplateFactoryMap[EMyDataTypes::FLOAT8] = boost::bind(boost::factory<UClassFactoryTemplate<float>*>());
ClassDataTypeTemplateFactoryMap[EMyDataTypes::FLOAT16] = boost::bind(boost::factory<UClassFactoryTemplate<double>*>());
}
std::unique_ptr<IBaseClass> UClassFactory::CreateConcreteClass(string ClassString, std::unique_ptr<IBaseClass> LeftVal, std::unique_ptr<IBaseClass> RightVal, EMyDataTypes someEnumVal)
{
std::unique_ptr<UBaseClassTemplateFactory> BaseOperatorTempFactory{ ClassDataTypeTemplateFactoryMap.at(someEnumVal) };
return BaseOperatorTempFactory->Get()::CreateClassTemplatized(ClassString, LeftVal, RightVal);
}
The question now is, the above code does not even compile let alone run, it says abstract class cannot be instantiated for the templatized map. I just want the UClassFactory to return me correct instantiated class like A,B,C based on a string map with correct datatypes based on an enum. How do I achieve this combination? I wonder what is the correct syntax? Or is my approach inherently flawed? Or there is a nice way to instantiate classes with factory pattern and different datatypes? Please let me know any suggestions/ comments.
Thanks
Alam

Is it possible to implement a copyable_unique_ptr that is not affected by slicing?

Regardless of the fact that copying a unique_ptr makes sense or not*, I tried to implement this kind of class, simply wrapping a std::unique_ptr, and got into difficulty exactly where the copy is taken, in the case of a smart pointer to base and the stored object being a derived class.
A naive implementation of the copy constructor can be found all over the internet (data is the wrapped std::unique_ptr):
copyable_unique_ptr::copyable_unique_ptr(const copyable_unique_ptr& other)
: data(std::make_unique(*other.get()) // invoke the class's copy constructor
{}
Problem here is, that due to the left out template arguments, is that the copy creates an instance of the type T, even if the real type is U : T. This leads to loss of information on a copy, and although I understand perfectly well why this happens here, I can't find a way around this.
Note that in the move case, there is no problem. The original pointer was created properly somewhere in user code, and moving it to a new owner doesn't modify the object's real type. To make a copy, you need more information.
Also note that a solution employing a clone function (thus infecting the type T's interface) is not what I would find to be acceptable.
*if you want a single owning pointer to a copyable resource this can make sense and it provides much more than what a scoped_ptr or auto_ptr would provide.
After some struggling with getting all the magic incantations right so that a good C++ compiler is satisfied with the code, and I was satisfied with the semantics, I present to you, a (very barebones) value_ptr, with both copy and move semantics. Important to remember is to use make_value<Derived> so it picks up the correct copy function, otherwise a copy will slice your object. I did not find an implementation of a deep_copy_ptr or value_ptr that actually had a mechanism to withstand slicing. This is a rough-edged implementation that misses things like the fine-grained reference handling or array specialization, but here it is nonetheless:
template <typename T>
static void* (*copy_constructor_copier())(void*)
{
return [](void* other)
{ return static_cast<void*>(new T(*static_cast<T*>(other))); };
}
template<typename T>
class smart_copy
{
public:
using copy_function_type = void*(*)(void*);
explicit smart_copy() { static_assert(!std::is_abstract<T>::value, "Cannot default construct smart_copy for an abstract type."); }
explicit smart_copy(copy_function_type copy_function) : copy_function(copy_function) {}
smart_copy(const smart_copy& other) : copy_function(other.get_copy_function()) {}
template<typename U>
smart_copy(const smart_copy<U>& other) : copy_function(other.get_copy_function()) {}
void* operator()(void* other) const { return copy_function(other); }
copy_function_type get_copy_function() const { return copy_function; }
private:
copy_function_type copy_function = copy_constructor_copier<T>();
};
template<typename T,
typename Copier = smart_copy<T>,
typename Deleter = std::default_delete<T>>
class value_ptr
{
using pointer = std::add_pointer_t<T>;
using element_type = std::remove_reference_t<T>;
using reference = std::add_lvalue_reference_t<element_type>;
using const_reference = std::add_const_t<reference>;
using copier_type = Copier;
using deleter_type = Deleter;
public:
explicit constexpr value_ptr() = default;
explicit constexpr value_ptr(std::nullptr_t) : value_ptr() {}
explicit value_ptr(pointer p) : data{p, copier_type(), deleter_type()} {}
~value_ptr()
{
reset(nullptr);
}
explicit value_ptr(const value_ptr& other)
: data{static_cast<pointer>(other.get_copier()(other.get())), other.get_copier(), other.get_deleter()} {}
explicit value_ptr(value_ptr&& other)
: data{other.get(), other.get_copier(), other.get_deleter()} { other.release(); }
template<typename U, typename OtherCopier>
value_ptr(const value_ptr<U, OtherCopier>& other)
: data{static_cast<pointer>(other.get_copier().get_copy_function()(other.get())), other.get_copier(), other.get_deleter()} {}
template<typename U, typename OtherCopier>
value_ptr(value_ptr<U, OtherCopier>&& other)
: data{other.get(), other.get_copier(), other.get_deleter()} { other.release(); }
const value_ptr& operator=(value_ptr other) { swap(data, other.data); return *this; }
template<typename U, typename OtherCopier, typename OtherDeleter>
value_ptr& operator=(value_ptr<U, OtherCopier, OtherDeleter> other) { std::swap(data, other.data); return *this; }
pointer operator->() { return get(); }
const pointer operator->() const { return get(); }
reference operator*() { return *get(); }
const_reference operator*() const { return *get(); }
pointer get() { return std::get<0>(data); }
const pointer get() const { return std::get<0>(data); }
copier_type& get_copier() { return std::get<1>(data); }
const copier_type& get_copier() const { return std::get<1>(data); }
deleter_type& get_deleter() { return std::get<2>(data); }
const deleter_type& get_deleter() const { return std::get<2>(data); }
void reset(pointer new_data)
{
if(get())
{
get_deleter()(get());
}
std::get<0>(data) = new_data;
}
pointer release() noexcept
{
pointer result = get();
std::get<0>(data) = pointer();
return result;
}
private:
std::tuple<pointer, copier_type, deleter_type> data = {nullptr, smart_copy<T>(), std::default_delete<T>()};
};
template<typename T, typename... ArgTypes>
value_ptr<T> make_value(ArgTypes&&... args)
{
return value_ptr<T>(new T(std::forward<ArgTypes>(args)...));;
}
Code lives here and tests to show how it should work are here for everyone to see for themselves. Comments always welcome.

Get template to work well with unique_ptr to interfaces in C++

First of all, there's no such built in concept as "interface". By interface in C++, I really mean some abstract base class that looks like:
struct ITreeNode
{
... // some pure virtual functions
};
Then we can have concrete structs that implement the interface, such as:
struct BinaryTreeNode : public ITreeNode
{
BinaryTreeNode* LeftChild;
BinaryTreeNode* RightChild;
// plus the overriden functions
};
It makes good sense: ITreeNode is an interface; not every implementation has Left & Right children - only BinaryTreeNode does.
To make things widely reusable, I want to write a template. So the ITreeNode needs to be ITreeNode<T>, and BinaryTreeNode needs to be BinaryTreeNode<T>, like this:
template<typename T>
struct BinaryTreeNode : public ITreeNode<T>
{
};
To make things even better, let's use unique pointer(smart point is more common, but I know the solution - dynamic_pointer_cast).
template<typename T>
struct BinaryTreeNode : public ITreeNode<T>
{
typedef std::shared_ptr<BinaryTreeNode<T>> SharedPtr;
typedef std::unique_ptr<BinaryTreeNode<T>> UniquePtr;
// ... other stuff
};
Likewise,
template<typename T>
struct ITreeNode
{
typedef std::shared_ptr<ITreeNode<T>> SharedPtr;
typedef std::unique_ptr<ITreeNode<T>> UniquePtr;
};
It's all good, until this point:
Let's assume now we need to write a class BinaryTree.
There's a function insert that takes a value T and insert it into the root node using some algorithm(naturally it will be recursive).
In order to make the function testable, mockable and follow good practice, the arguments need to be interface, rather than concrete classes. (Let's say this is a rigid rule that cannot be broken.)
template<typename T>
void BinaryTree<T>::Insert(const T& value, typename ITreeNode<T>::UniquePtr& ptr)
{
Insert(value, ptr->Left); // Boooooom, exploded
// ...
}
Here's the problem:
Left is not a field of ITreeNode! And worst of all, you cannot cast a unique_ptr<Base> to unique_ptr<Derived>!
What's the best practice for a scenario like this?
Thanks a lot!
Ok, over-engineering it is! But note that, for the most part, such low level data structures benefit HUGELY from transparency and simple memory layouts. Placing the level of abstraction above the container can give significant performance boosts.
template<class T>
struct ITreeNode {
virtual void insert( T const & ) = 0;
virtual void insert( T && ) = 0;
virtual T const* get() const = 0;
virtual T * get() = 0;
// etc
virtual ~ITreeNode() {}
};
template<class T>
struct IBinaryTreeNode : ITreeNode<T> {
virtual IBinaryTreeNode<T> const* left() const = 0;
virtual IBinaryTreeNode<T> const* right() const = 0;
virtual std::unique_ptr<IBinaryTreeNode<T>>& left() = 0;
virtual std::unique_ptr<IBinaryTreeNode<T>>& right() = 0;
virtual void replace(T const &) = 0;
virtual void replace(T &&) = 0;
};
template<class T>
struct BinaryTreeNode : IBinaryTreeNode<T> {
// can be replaced to mock child creation:
std::function<std::unique_ptr<IBinaryTreeNode<T>>()> factory
= {[]{return std::make_unique<BinaryTreeNode<T>>();} };
// left and right kids:
std::unique_ptr<IBinaryTreeNode<T>> pleft;
std::unique_ptr<IBinaryTreeNode<T>> pright;
// data. I'm allowing it to be empty:
std::unique_ptr<T> data;
template<class U>
void insert_helper( U&& t ) {
if (!get()) {
replace(std::forward<U>(t));
} else if (t < *get()) {
if (!left()) left() = factory();
assert(left());
left()->insert(std::forward<U>(t));
} else {
if (!right()) right() = factory();
assert(right());
right()->insert(std::forward<U>(t));
}
}
// not final methods, allowing for balancing:
virtual void insert( T const&t ) override { // NOT final
return insert_helper(t);
}
virtual void insert( T &&t ) override { // NOT final
return insert_helper(std::move(t));
}
// can be empty, so returns pointers not references:
T const* get() const override final {
return data.get();
}
T * get() override final {
return data.get();
}
// short, could probably skip:
template<class U>
void replace_helper( U&& t ) {
data = std::make_unique<T>(std::forward<U>(t));
}
// only left as customization points if you want.
// could do this directly:
virtual void replace(T const & t) override final {
replace_helper(t);
}
virtual void replace(T && t) override final {
replace_helper(std::move(t));
}
// Returns pointers, because no business how we store it in a const
// object:
virtual IBinaryTreeNode<T> const* left() const final override {
return pleft.get();
}
virtual IBinaryTreeNode<T> const* right() const final override {
return pright.get();
}
// returns references to storage, because can be replaced:
// (could implement as getter/setter, but IBinaryTreeNode<T> is
// "almost" an implementation class, some leaking is ok)
virtual std::unique_ptr<IBinaryTreeNode<T>>& left() final override {
return pleft;
}
virtual std::unique_ptr<IBinaryTreeNode<T>>& right() final override {
return pright;
}
};

Resources