Policies conversion works only with constructor - c++

#include "stdafx.h"
#include <exception>
template<class T>
class NoCheck;
template<class T>
class EnforceNotNull
{
public:
//EnforceNotNull(const NoCheck<T>&){}//<<-----If this is uncommented it works
static void Check(T* p)
{
class NullPtrException : public std::exception
{
};
if (!p)
{
throw NullPtrException();
}
}
};
template<class T>
class NoCheck
{
public:
NoCheck(){}
NoCheck(const NoCheck&){}
NoCheck(const EnforceNotNull<T>&){}
operator EnforceNotNull<T>() {return EnforceNotNull<T>();}//<<-----This seams to not do its job
static void Check(T* p)
{/*Empty body*/}
};
template<class T, template<class> class CheckingPolicy>
class SmartPtr : public CheckingPolicy<T>
{
public:
SmartPtr(T* p)
{
Check(p);
}
template<class T1, template <class> class CheckingPolicy1>
SmartPtr(const SmartPtr<T1,CheckingPolicy1>& pattern):pointee_(pattern.pointee_),
CheckingPolicy<T>(pattern)
{
}
T* pointee_;
private:
};
int _tmain(int argc, _TCHAR* argv[])
{
SmartPtr<int,NoCheck> p1(nullptr);
SmartPtr<int,EnforceNotNull> p = p1;//I'm trying here to convert NoCheck to
// EnforceNotNull but it works for me only if I use ctor, if I use conversion optor
//(from
// NoCheck to EnforceNotNull) it doesn't work why?
return 0;
}

I don't see why the SmartPtr has to be inherited from the checking policy at all. Nor do I see why the policy has to be a template itself.
Why not simply:
#include <cstdlib>
#include <exception>
class EnforceNotNull
{
public:
template <class T>
static void Check(T* p)
{
class NullPtrException : public std::exception
{
};
if (!p)
{
throw NullPtrException();
}
}
};
class NoCheck
{
public:
template<class T>
static void Check(T* p)
{/*Empty body*/}
};
template<class T, class CheckingPolicy>
class SmartPtr
{
public:
SmartPtr(T* p)
{
CheckingPolicy::Check(p);
}
template<class T1, class CheckingPolicy1>
SmartPtr(const SmartPtr<T1,CheckingPolicy1>& pattern):pointee_(pattern.pointee_)
{
CheckingPolicy::Check(pointee_); //pattern's pointee_ may not pass our check
}
T* pointee_;
private:
};
int main()
{
SmartPtr<int,NoCheck> p1(NULL);
SmartPtr<int,EnforceNotNull> p = p1;
return 0;
}

Your operator EnforceNotNull<T>() function is not const, so the compiler isn't including it in the set of possible conversion functions. Uncomment EnforceNotNull copy ctor or put a const on the above function and your code should work.

Your code looks a little bit overcomplicated. For example, you don't have to inherit a policy unless it cares some state, which is not your case. Plus, having classes requires putting access specifiers, so you might be better off with structs.
Anyways, smart pointers cannot be copied, that is the main trick. You can only transfer ownership (movable concept). So your copy constructor is a bit incorrect. You may still have it if that is clearly your intent, but make sure you have some reference counter whatsoever.
Here is your code, simplified and working:
#include <cstdio>
#include <cstddef>
#include <exception>
class NullPtrException : public std::exception
{
};
template <typename T>
struct EnforceNotNull
{
static void Check(T *p)
{
if (p == NULL)
{
throw NullPtrException();
}
}
};
template <typename T>
struct NoCheck
{
static void Check(T *)
{
}
};
template <typename T, template <typename> class CheckingPolicy>
class SmartPtr
{
T* pointee_;
public:
SmartPtr (T* p) :
pointee_ (p)
{
CheckingPolicy<T>::Check (pointee_);
}
template <typename T1, template <typename> class CheckingPolicy1>
SmartPtr (SmartPtr<T1, CheckingPolicy1> & pattern) :
pointee_ (pattern.get ())
{
CheckingPolicy<T>::Check (pointee_);
pattern.release ();
}
~SmartPtr ()
{
delete pointee_;
pointee_ = NULL;
}
T *get ()
{
return pointee_;
}
T *release ()
{
T *result = pointee_;
pointee_ = NULL;
return result;
}
};
int main()
{
try
{
printf ("Creating NULL pointer...\n");
SmartPtr<int, NoCheck> p1 (NULL);
printf ("Changing policy... \n");
SmartPtr<int, EnforceNotNull> p = p1;
printf ("This doesn't work :-(\n");
}
catch (const NullPtrException &)
{
printf ("GOTCHA!!!\n");
}
}
Here is how you enforce conversions using MPL:
#include <cstdio>
#include <cstddef>
#include <exception>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/or.hpp>
class NullPtrException : public std::exception {};
struct EnforceNotNull
{
template <typename T>
static void Check(T *p)
{
if (p == NULL)
throw NullPtrException();
}
};
struct NoCheck
{
template <typename T>
static void Check(T *) {}
};
template <typename T, typename CheckingPolicy>
class SmartPtr
{
T* p_;
public:
SmartPtr (T* p) :
p_ (p)
{
CheckingPolicy::Check (p_);
}
template <typename T1, typename PolicyT>
SmartPtr (SmartPtr<T1, PolicyT> & ptr,
// Enable moving from no checking pointer to any pointer
// or checking pointer to checking pointer.
// This makes it impossible to transfer checking to non-checking pointer.
typename boost::enable_if< boost::mpl::or_ <
boost::is_same<PolicyT, NoCheck>,
boost::is_same<PolicyT, CheckingPolicy> > >::type *dummy = NULL) :
p_ (ptr.get ())
{
CheckingPolicy::Check (p_);
ptr.release ();
}
~SmartPtr ()
{
delete p_;
p_ = NULL;
}
T *get () const
{
return p_;
}
T *release ()
{
T *result = p_;
p_ = NULL;
return result;
}
};
int main()
{
try
{
SmartPtr<int, NoCheck> p1 (NULL);
SmartPtr<int, EnforceNotNull> p2 = p1;
// SmartPtr<int, NoCheck> p3 = p2; // This will not compile.
}
catch (const NullPtrException &)
{
printf ("GOTCHA!!!\n");
}
}

Related

Type erasure and a kind of template method pattern

Consider the following, minimal example:
struct S {
using func_t = void(*)(void *);
template<typename T>
static void proto(void *ptr) {
static_cast<T*>(ptr)->f();
}
func_t func;
void *ptr;
};
struct T {
void f() {}
};
void g(S &s) {
s.func(s.ptr);
}
int main() {
T t;
S s;
s.func = &S::proto<T>;
s.ptr = &t;
g(s);
}
The pretty obvious idea is to erase the type of a bunch of objects (like T, that is not the only available type) to create an array of instances of S, then iterate over that array and invoke a predetermined member function.
So far so good, it's easy to implement and it works.
Now I would like to provide an external function to be invoked on the erased object, something that would be like this:
template<typename T, typename F>
static void proto(void *ptr, F &&f) {
auto *t = static_cast<T*>(ptr);
std::forward<F>(f)(*t);
t->f();
}
Or this:
template<typename T>
static void proto(void *ptr, void(*f)(T &)) {
auto *t = static_cast<T*>(ptr);
f(*t);
t->f();
}
To be invoked as:
s.func(s.ptr, [](auto obj){ /* ... */ });
A kind of template method pattern where the extra functionalities are provided by the caller instead of a derived class.
Unfortunately I cannot do that for I cannot reduce the specializations to something homogeneous to be assigned to a function pointer.
The only alternative I can see is to define a custom class like the following one:
struct C {
template<typename T>
void f(T &t) { /* ... */ }
// ...
};
Where f dispatches somehow the call internally to the right member function, then use it as:
struct S {
using func_t = void(*)(void *, C &);
template<typename T>
static void proto(void *ptr, C &c) {
auto t = static_cast<T*>(ptr);
c.f(*t);
t->f();
}
func_t func;
void *ptr;
};
That is not far from what I would do by using a lambda, but it's more verbose and requires me to explicitly declare the class C.
Is there any other valid alternative to achieve the same or is this the only viable solution?
Assuming you can enumerate the types you wish to support you can do this:
#include <iostream>
#include <string>
#include <vector>
template <class... Ts>
struct PseudoFunction {
private:
template <class T>
static void (*function)(T &);
template <class T>
static void call_func(void *object) {
return function<T>(*static_cast<T *>(object));
}
template <class Fun>
static void assign(Fun) {}
template <class Fun, class Head, class... Tail>
static void assign(Fun fun) {
function<Head> = fun;
assign<Fun, Tail...>(fun);
}
public:
template <class T>
PseudoFunction(T *t)
: object(t)
, func(call_func<T>) {}
template <class F>
static void set_function(F f) {
assign<F, Ts...>(f);
}
void operator()() {
func(object);
}
private:
void *object;
void (*func)(void *);
};
template <class... Ts>
template <class T>
void (*PseudoFunction<Ts...>::function)(T &) = nullptr;
//example types that are not related and not copy constructible
//but have the same member function name and signature
struct T1 {
T1() = default;
T1(const T1 &) = delete;
void func(double d) {
std::cout << "T1: " + std::to_string(d) + '\n';
}
};
struct T2 {
T2() = default;
T2(const T2 &) = delete;
void func(double d) {
std::cout << "T2: " + std::to_string(d) + '\n';
}
};
int main() {
T1 t1;
T2 t2;
using PF = PseudoFunction<T1, T2>;
std::vector<PF> funcs;
funcs.push_back(&t1);
funcs.push_back(&t2);
PF::set_function([](auto &object) { object.func(3.14); });
for (auto &f : funcs) {
f();
}
}
(demo)
It has decent call syntax (just that you have to specify the function before calling the objects) and some overhead of setting potentially unused function pointers.
One could probably make a wrapper that does the set_function and iterating over the PFs in one go.

accessing members of a templated class with variable numbers of templated arguments

I have a templated class with variable numbers of templated arguments. As in these cases (I cannot afford C++11) a good practice is to create a default class that we call none and put it as default like below.
struct none {};
template<class T1=none, T2=none, T3=none>
class A{
template<class T>
double extract() { return none();}
template<>
double extract<T1>() { return m1_();}
template<>
double extract<T2>() { return m2_();}
template<>
double extract<T3> () { return m3_();}
T1 m1_;
T2 m2_;
T3 m3_;
};
At this stage I don't know how to implement a generic/templated accessor function that can access each of the templated argument.
All of the templated arguments are different so I specialized A::extract() for each of the templated arguments.
Is there any better way to do this? Any sort of tagging I can have a look at?
struct none {};
template <class T, class N>
class Holder : public N
{
protected:
T m;
typedef Holder<T, N> First;
double extractP(T*) { return m(); }
template <class X> double extractP(X*) {
return this->N::extractP(static_cast<X*>(0));
}
};
template <class T>
class Holder<T, none>
{
protected:
T m;
typedef Holder<T, none> First;
double extractP(T*) { return m(); }
template <class X> none extractP(X*) {
return none();
}
};
template <class T1 = none, class T2 = none, class T3 = none>
class A : Holder<T1, Holder<T2, Holder<T3, none> > >
{
public:
template <class T> double extract() {
return this->extractP(static_cast<T*>(0));
}
};
A similarly-named solution to n.m but more on the Boost's Variant class design.
The suggestion is to use a Variant container (a generic container for your objects) and use accessors directly on them.
#include <iostream>
#include <stdexcept>
using namespace std;
class BaseHolder
{
public:
virtual ~BaseHolder(){}
virtual BaseHolder* clone() const = 0;
};
template<typename T>
class HoldData : public BaseHolder
{
public:
HoldData(const T& t_) : t(t_){}
virtual BaseHolder* clone() const {
return new HoldData<T>(t);
}
T getData() {
return t;
}
private:
T t;
};
class Variant
{
public:
Variant() : data(0) {}
template<typename T>
Variant(const T& t) : data(new HoldData<T>(t)){}
Variant(const Variant& other) : data(other.data ? other.data->clone() : 0) {}
~Variant(){delete data;}
template<typename T>
T getData() {
return ((HoldData<T>*)data)->getData();
}
private:
BaseHolder* data;
private:
Variant& operator=(const Variant& other) { return *this;} // Not allowed
};
struct none {};
class Container{
public:
Container() : m1_(0), m2_(0), m3_(0){}
~Container() {
if(m1_)
delete m1_;
if(m2_)
delete m1_;
if(m3_)
delete m1_;
}
none extract() { return none();}
template<typename T>
void insertM1(T obj) {
m1_ = new Variant(obj);
}
template<typename T>
T extractM1() {
if(m1_ != 0)
return m1_->getData<T>();
else
throw std::runtime_error("Element not set");
}
// TODO: implement m2 and m3
Variant *m1_;
Variant *m2_;
Variant *m3_;
};
int main() {
Container obj;
char M1 = 'Z';
obj.insertM1(M1);
char extractedM1 = obj.extractM1<char>();
cout << extractedM1;
return 0;
}
http://ideone.com/BaCWSV
Your class seems to mimic std::tuple, which, unfortunately for you, was added in C++11. The good news is that you can use boost::tuple instead.
As an example of usage:
boost::tuple<std::string, double> t = boost::make_tuple("John Doe", 4.815162342);
std::cout << boost::get<0>(t) << '\n';
std::cout << boost::get<1>(t) << '\n';
Live demo
Without access to C++11, it's a bit uglier, but you can leverage Boost.Tuple:
#include <iostream>
#include <boost/tuple/tuple.hpp>
template <size_t I, typename T, typename U>
struct AccessImpl;
template <size_t I, typename T, typename U>
struct AccessImpl {
template <typename Tuple>
static T& impl(Tuple& tuple) {
typedef typename ::boost::tuples::element<I+1, Tuple>::type Next;
return AccessImpl<I+1, T, Next>::impl(tuple);
}
};
template <size_t I, typename T>
struct AccessImpl<I, T, T> {
template <typename Tuple>
static T& impl(Tuple& tuple) { return boost::get<I>(tuple); }
};
template <typename T, typename Tuple>
T& access(Tuple& tuple) {
typedef typename ::boost::tuples::element<0, Tuple>::type Head;
return AccessImpl<0, T, Head>::impl(tuple);
}
int main() {
boost::tuples::tuple<char, int, std::string> example('a', 1, "Hello, World!");
std::cout << access<std::string>(example) << "\n";
return 0;
}
This, as expected, prints "Hello, World!".

Accessing a member in a template: how to check if the template is a pointer or not?

Given the following declaration:
template<class T>
class A {
void run(T val) {
val.member ...
}
}
This code works fine if no pointers are used:
A<Type> a;
Type t;
a.run(t);
But using a pointer results in an error:
A<Type*> a;
Type* t = new Type();
a.run(t);
error: request for member ‘member’ which is of non-class type ‘T*’
Obviously in this case the member must be accessed via ->. What's the best way to handle this?
I found a solution on SO: Determine if Type is a pointer in a template function
template<typename T>
struct is_pointer { static const bool value = false; };
template<typename T>
struct is_pointer<T*> { static const bool value = true; };
...
if (is_pointer<T>::value) val->member
else val.member
But this is very verbose. Any better ideas?
You could use a simple pair of overloaded function templates:
template<typename T>
T& access(T& t) { return t; }
template<typename T>
T& access(T* t) { return *t; }
And then use them this way:
access(val).member = 42;
For instance:
template<typename T>
struct A
{
void do_it(T& val)
{
access(val).member = 42;
}
};
struct Type
{
int member = 0;
};
#include <iostream>
int main()
{
A<Type> a;
Type t;
a.do_it(t);
std::cout << t.member << std::endl;
A<Type*> a2;
Type* t2 = new Type(); // OK, I don't like this, but just to show
// it does what you want it to do...
a2.do_it(t2);
std::cout << t2->member;
delete t2; // ...but then, don't forget to clean up!
}
Here is a live example.
The best idea is probably to specialize your class for pointer types.
template<class T>
class A{ ...};
template<>
class A<T*> { //implement for pointers
};
If you feel that this is too verbose, you can use overload a get_ref function:
template<class T> T& get_ref(T & r) {return r;}
template<class T> T& get_ref(T* r) {return *r;}
template<class T>
class A {
void do(T val) {
get_ref(val).member ...
}
}

C++. How to define template parameter of type T for class A when class T needs a type A template parameter?

Executor class has template of type P and it takes a P object in constructor. Algo class has a template E and also has a static variable of type E. Processor class has template T and a collection of Ts.
Question how can I define Executor< Processor<Algo> > and Algo<Executor> ? Is this possible? I see no way to defining this, its kind of an "infinite recursive template argument"
See code.
template <class T>
class Processor {
map<string,T> ts;
void Process(string str, int i)
{
ts[str].Do(i);
}
}
template <class P>
class Executor {
P &p;
Executor(P &inp) : p(inp) {}
void Bar(string str, int i) {
p.Process(str,i);
}
Execute(string str)
{
}
}
template <class E>
class Algo
{
static E e;
void Do(int i) {}
void Foo()
{
e.Execute("xxx");
}
}
main ()
{
typedef Processor<Algo> PALGO; // invalid
typedef Executor<PALGO> EPALGO;
typedef Algo<EPALGO> AEPALGO;
Executor<PALGO> executor(PALGO());
AEPALGO::E = executor;
}
EDIT ****************************
A little clarification. Executor is a singleton that provides a service. All Algo objects need the services of Executor. Executor will sometimes generate reports that need to be sent to a specific Algo object. They get sent to the correct Algo through Processor.
Basic issue is that Algo is needed to define Executor and Executor is needed to define Algo.
Tried reproducing your code, not quite sure what you are trying to achieve. For starters, this is what I modified it to:
#include <string> //Added
#include <map> //Added
using namespace std;//Added
template <class T>
class Processor {
map<string,T> ts;
void Process(string str, int i) {
ts[str].Do(i);
}
};
template <class P>
class Executor {
Processor<P> &p; //Was Proc ???
Executor(P &p) : Processor<P>(p) {} //Was Proc ???
void Foo(string str, int i) {
p.Process(str,i);
}
void Execute(string str){} //Added return type void
};
template <class E>
class Algo {
public: //Added
static E e;
void Do(int i) {}
};
main () {
typedef Processor< Algo<int> > PALGO; //Added template argument to Algo
typedef Executor<PALGO> EPALGO;
typedef Algo<EPALGO> AEPALGO;
Executor<PALGO> executor(PALGO());
AEPALGO::e = executor;
}
Modified Proc to Processor in Executor definition - (what is Proc?) and gave it template argument, in the typedef Processor> PALGO;
Then AEPAGO::E --> thats a template param, not class Algo member - so AEPAGO::e.
Now you will get an error that can be more manageable. It needs a copy constructor to convert types.
You can use inheritance.
class X : public Executor<Processor<Algo<X>>> {};
Else, this is not possible.
AFAICS, you cannot do that with the same Executor type. Otherwise you would have to define
Executor<Processor<Algo<Executor<Processor<Algo<...> > > > > >
It might work, if you define it with some other type, provided that makes any sense technically
class X {
...
};
Executor<Processor<Algo<Executor<Processor<Algo<X> > > > > >
or with typedef
class X {...};
typedef Processor<Algo<X> > PALGO;
typedef Executor<PALGO> EPALGO;
typedef Algo<EPALGO> AEPALGO;
Executor<PALGO> executor(PALGO());
Since Executor is a singleton, you can move its definition out of Algo either in it's own singleton class or in Executor. Then make all the Algo function that need to know about Executor template member functions.
template <class P>
class Executor {
static Executor e;
P &p;
Executor(P &p) : Proc(p) {}
void Bar(string str, int i) {
p.Process(str,i);
}
Execute(string str)
{
}
public:
static Executor& getE(){ return e;}
}
class Algo
{
void Do(int i) {}
template <class E>
void Foo()
{
E::getE().Execute("xxx");
}
}
Solved! see comments. //****
#include <string>
#include <map>
#include <iostream>
using namespace std;
template <class T>
class Processor {
public:
map<string,T*> ts;
void Process(string str, int i)
{
ts[str]->Do(i);
}
};
template <class P>
class Executor {
public:
P &p;
Executor(P &inp) : p(inp) {}
void Bar(string str, int i) {
p.Process(str,i);
}
void Execute(string str)
{
cout << " Executor::Execute " << str << endl;
}
};
template <template <class> class E> //**********
class Algo
{
string str;
public:
Algo(const string &s) : str(s) {}
static E<Processor<Algo>> *e; //**********
void Do(int i) { cout << str << "::Do(" << i <<")"<< endl; }
void Foo()
{
e->Execute(str);
}
};
template <template <class> class E>
E< Processor<Algo<E> > >* Algo<E>::e; //**********
int main(int argc, char **argv)
{
typedef Algo<Executor> EALGO;
typedef Processor<EALGO> PALGO;
typedef Executor<PALGO> EPALGO;
PALGO p;
EPALGO executor(p);
EALGO::e = &executor; //**********
EALGO ealgo1("algo1"), ealgo2("algo2");
p.ts["algo1"] = &ealgo1;
p.ts["algo2"] = &ealgo2;
ealgo1.Foo();
ealgo2.Foo();
executor.Bar("algo1",1111);
executor.Bar("algo2",2222);
}

boost concept check operator() overload

template <typename T, typename C>
class CSVWriter{
template <typename PrinterT>
void write(std::ostream& stream, const PrinterT& printer){
}
};
I want to check whether there exists at least two overloads PrinterT::operator()(T*) and PrinterT::operator()(C*)
PrinterT may or may not inherit from std::unary_function
What concept Checking Classes I need to use here ?
(I am not using C++11)
You can use something like that
#include <iostream>
#include <boost/concept/requires.hpp>
#include <boost/concept/usage.hpp>
template <class Type, class Param>
class has_operator_round_brackets_with_parameter
{
public:
BOOST_CONCEPT_USAGE(has_operator_round_brackets_with_parameter)
{
_t(_p);
}
private:
Type _t;
Param _p;
};
struct X {};
struct Y {};
struct Test1
{
void operator() (X*) const { }
};
struct Test2: public Test1
{
void operator() (X*) const { }
void operator() (Y*) const { }
};
template <class T, class C>
struct CSVWriter
{
template <class PrinterT>
BOOST_CONCEPT_REQUIRES(
((has_operator_round_brackets_with_parameter<PrinterT, T*>))
((has_operator_round_brackets_with_parameter<PrinterT, C*>)),
(void)) write(std::ostream& stream, const PrinterT& printer)
{
}
};
int main()
{
CSVWriter<X, Y> w;
// w.write<Test1>(std::cout, Test1()); // FAIL
w.write<Test2>(std::cout, Test2()); // OK
return 0;
}