Can you tell me how to create an object for the exponential_distribution distribution, where I would specify only the minimum and maximum values that can be taken in this distribution as input parameters?
m_generatorDeltaTime = std::exponential_distribution<double>(minDelta, maxDelta);
the example above gives an error:(
An exponential distribution has only one parameter, which determines it's shape.
The minimum is always 0, and there is no maximum.
You can write your own distribution object, and use std::exponential_distribution as part of it.
template <typename RealType>
struct my_distribution
{
struct param_type : typename std::exponential_distribution<RealType>::param_type
{
RealType min;
RealType max;
};
using result_type = RealType
my_distribution(RealType lambda, RealType min, RealType max) : m_exp(lambda), m_param(lambda, min, max) {}
my_distribution(param_type param) : m_exp(param), m_param(param) {}
template <typename URBG>
result_type operator()(URBG & gen)
{
result_type initial = m_exp(gen);
// some calculation of value here involving m_param.min, m_param.max
return value;
}
template <typename URBG>
result_type operator()(URBG & gen, const param_type & param)
{
result_type initial = m_exp(gen, param);
// some calculation of value here involving param.min, param.max
return value;
}
param_type param() { return m_param; }
void param(const param_type & param) { m_exp.param(param); m_param = param; }
result_type lambda() { return m_exp.lambda(); }
result_type min() { return m_param.min; }
result_type max() { return m_param.max; }
private:
std::exponential_distribution<RealType> m_exp;
param_type m_param;
}
Related
I'm looking into a solution of building containers which track stored size of their elements in addition to basic functions.
So far I didn't saw a solution which doesn't create a huge amount of boilerplate code of each invalidating member of container. This also assumes that stored elements cannot change size after being stored.
Unless standard containers have some feature that allows to inject such behaviour. The following example should be working one, albeit abridged for brevity. The declarations used are:
typedef uint8_t Byte;
typedef Byte PacketId;
template <class T>
struct CollectionTraits {
typedef T collection_type;
typedef typename collection_type::value_type value_type;
typedef typename collection_type::size_type size_type;
typedef typename collection_type::iterator iterator;
typedef typename collection_type::reference reference;
typedef typename collection_type::const_iterator const_iterator;
const_iterator begin() const { return _collection.begin(); }
const_iterator end() const { return _collection.end(); }
iterator begin() { return _collection.begin(); }
iterator end() { return _collection.end(); }
size_type size() const { return _collection.size(); }
protected:
T _collection;
};
struct Packet : CollectionTraits<std::vector<Byte>>
{
PacketId id;
};
The container itself:
struct PacketList : CollectionTraits<std::deque<Packet>>
{
public:
typedef Packet::size_type data_size;
void clear() { _collection.clear(); _total_size = 0; }
data_size total_size() const { return _total_size; }
void push_back(const Packet& v) {
_collection.push_back(v);
_add(v);
}
void push_back(const Packet&& v) {
_collection.push_back(std::move(v));
_add(v);
}
void push_front(const Packet& v) {
_collection.push_front(v);
_add(v);
}
void push_front(const Packet&& v) {
_collection.push_front(std::move(v));
_add(v);
}
void pop_back() {
_remove(_collection.back());
_collection.pop_back();
}
void erase(const_iterator first, const_iterator last) {
for(auto it = first; it != last; ++it) _remove(*it);
_collection.erase(first, last);
}
PacketList() : _total_size(0) {}
PacketList(const PacketList& other) : _total_size(other._total_size) {}
private:
void _add(const Packet& v) { _total_size += v.size(); }
void _remove(const Packet& v) { _total_size -= v.size(); }
data_size _total_size;
};
The interface in result should similar to a standard container. Is there a way to avoid this amount of repeated code? Is there some standard solution for this problem?
I have an application with several boost::variants which share many of the fields. I would like to be able to compose these visitors into visitors for "larger" variants without copying and pasting a bunch of code. It seems straightforward to do this for non-recursive variants, but once you have a recursive one, the self-references within the visitor (of course) point to the wrong class. To make this concrete (and cribbing from the boost::variant docs):
#include "boost/variant.hpp"
#include <iostream>
struct add;
struct sub;
template <typename OpTag> struct binop;
typedef boost::variant<
int
, boost::recursive_wrapper< binop<add> >
, boost::recursive_wrapper< binop<sub> >
> expression;
template <typename OpTag>
struct binop
{
expression left;
expression right;
binop( const expression & lhs, const expression & rhs )
: left(lhs), right(rhs)
{
}
};
// Add multiplication
struct mult;
typedef boost::variant<
int
, boost::recursive_wrapper< binop<add> >
, boost::recursive_wrapper< binop<sub> >
, boost::recursive_wrapper< binop<mult> >
> mult_expression;
class calculator : public boost::static_visitor<int>
{
public:
int operator()(int value) const
{
return value;
}
int operator()(const binop<add> & binary) const
{
return boost::apply_visitor( *this, binary.left )
+ boost::apply_visitor( *this, binary.right );
}
int operator()(const binop<sub> & binary) const
{
return boost::apply_visitor( *this, binary.left )
- boost::apply_visitor( *this, binary.right );
}
};
class mult_calculator : public boost::static_visitor<int>
{
public:
int operator()(int value) const
{
return value;
}
int operator()(const binop<add> & binary) const
{
return boost::apply_visitor( *this, binary.left )
+ boost::apply_visitor( *this, binary.right );
}
int operator()(const binop<sub> & binary) const
{
return boost::apply_visitor( *this, binary.left )
- boost::apply_visitor( *this, binary.right );
}
int operator()(const binop<mult> & binary) const
{
return boost::apply_visitor( *this, binary.left )
* boost::apply_visitor( *this, binary.right );
}
};
// I'd like something like this to compile
// class better_mult_calculator : public calculator
// {
// public:
// int operator()(const binop<mult> & binary) const
// {
// return boost::apply_visitor( *this, binary.left )
// * boost::apply_visitor( *this, binary.right );
// }
// };
int main(int argc, char **argv)
{
// result = ((7-3)+8) = 12
expression result(binop<add>(binop<sub>(7,3), 8));
assert( boost::apply_visitor(calculator(),result) == 12 );
std::cout << "Success add" << std::endl;
// result2 = ((7-3)+8)*2 = 12
mult_expression result2(binop<mult>(binop<add>(binop<sub>(7,3), 8),2));
assert( boost::apply_visitor(mult_calculator(),result2) == 24 );
std::cout << "Success mult" << std::endl;
}
I would really like something like that commented out better_mult_expression to compile (and work) but it doesn't -- because the this pointers within the base calculator visitor don't reference mult_expression, but expression.
Does anyone have suggestions for overcoming this or am I just barking down the wrong tree?
Firstly, I'd suggest the variant to include all possible node types, not distinguishing between mult and expression. This distinction makes no sense at the AST level, only at a parser stage (if you implement operator precedence in recursive/PEG fashion).
Other than that, here's a few observations:
if you encapsulate the apply_visitor dispatch into your evaluation functor you can reduce the code duplication by a big factor
your real question seems not to be about composing variants, but composing visitors, more specifically, by inheritance.
You can use using to pull inherited overloads into scope for overload resolution, so this might be the most direct answer:
Live On Coliru
struct better_mult_calculator : calculator {
using calculator::operator();
auto operator()(const binop<mult>& binary) const
{
return boost::apply_visitor(*this, binary.left) *
boost::apply_visitor(*this, binary.right);
}
};
IMPROVING!
Starting from that listing let's shave off some noise!
remove unncessary AST distinction (-40 lines, down to 55 lines of code)
generalize the operations; the <functional> header comes standard with these:
namespace AST {
template <typename> struct binop;
using add = binop<std::plus<>>;
using sub = binop<std::minus<>>;
using mult = binop<std::multiplies<>>;
using expr = boost::variant<int,
recursive_wrapper<add>,
recursive_wrapper<sub>,
recursive_wrapper<mult>>;
template <typename> struct binop { expr left, right; };
} // namespace AST
Now the entire calculator can be:
struct calculator : boost::static_visitor<int> {
int operator()(int value) const { return value; }
template <typename Op>
int operator()(AST::binop<Op> const& binary) const {
return Op{}(boost::apply_visitor(*this, binary.left),
boost::apply_visitor(*this, binary.right));
}
};
Here your variant can add arbitrary operations without even needing to touch the calculator.
Live Demo, 43 Lines Of Code
Like I mentioned starting off, encapsulate visitation!
struct Calculator {
template <typename... T> int operator()(boost::variant<T...> const& v) const {
return boost::apply_visitor(*this, v);
}
template <typename T>
int operator()(T const& lit) const { return lit; }
template <typename Op>
int operator()(AST::binop<Op> const& bin) const {
return Op{}(operator()(bin.left), operator()(bin.right));
}
};
Now you can just call your calculator, like intended:
Calculator calc;
auto result1 = calc(e1);
It will work when you extend the variant with operatios or even other literal types (like e.g. double). It will even work, regardless of whether you pass it an incompatible variant type that holds a subset of the node types.
To finish that off for maintainability/readability, I'd suggest making operator() only a dispatch function:
Full Demo
Live On Coliru
#include <boost/variant.hpp>
#include <iostream>
namespace AST {
using boost::recursive_wrapper;
template <typename> struct binop;
using add = binop<std::plus<>>;
using sub = binop<std::minus<>>;
using mult = binop<std::multiplies<>>;
using expr = boost::variant<int,
recursive_wrapper<add>,
recursive_wrapper<sub>,
recursive_wrapper<mult>>;
template <typename> struct binop { expr left, right; };
} // namespace AST
struct Calculator {
auto operator()(auto const& v) const { return call(v); }
private:
template <typename... T> int call(boost::variant<T...> const& v) const {
return boost::apply_visitor(*this, v);
}
template <typename T>
int call(T const& lit) const { return lit; }
template <typename Op>
int call(AST::binop<Op> const& bin) const {
return Op{}(call(bin.left), call(bin.right));
}
};
int main()
{
using namespace AST;
std::cout << std::boolalpha;
auto sub_expr = add{sub{7, 3}, 8};
expr e1 = sub_expr;
expr e2 = mult{sub_expr, 2};
Calculator calc;
auto result1 = calc(e1);
std::cout << "result1: " << result1 << " Success? " << (12 == result1) << "\n";
// result2 = ((7-3)+8)*2 = 12
auto result2 = calc(e2);
std::cout << "result2: " << result2 << " Success? " << (24 == result2) << "\n";
}
Still prints
result1: 12 Success? true
result2: 24 Success? true
I am trying to implement Matrix Addition using expression templates. I am facing some trouble. Here is my matrix code:
#include<iostream>
#include<vector>
#include<cassert>
template <typename T>
class MatrixExpression {
public:
double operator[](size_t i) const { return static_cast<T const&>(*this)[i];}
size_t size()const { return static_cast<T const&>(*this).size(); }
};
template<typename T>
class Matrix:public MatrixExpression<Matrix<T>>
{
std::vector<std::vector<T>> mat;
public:
Matrix(std::size_t m, std::size_t n):mat(m,std::vector<T>(n)){}
class Proxy
{
std::vector<T> vec;
public:
Proxy(std::vector<T> vec):vec(vec){ }
T operator[](std::size_t i){ return vec[i];}
//T &operator[](std::size_t i){ return vec[i];}
std::size_t size() const{ return vec.size(); }
};
Proxy operator[](std::size_t i) const { return Proxy(mat[i]); }
//Proxy &operator[](std::size_t i) { return Proxy(mat[i]); }
size_t size() const { return mat.size(); }
Matrix(std::initializer_list<std::initializer_list<T>> lst)
{
int m=0,n=0;
for(auto l:lst )
{
for(auto v:l)
{
n++;
}
m++;
}
int i=0,j=0;
mat(m,std::vector<T>(n));
for(auto l:lst )
{
for(auto v:l)
{
mat[i].push_back(v);
}
i++;
}
}
Matrix(MatrixExpression<T> const& matx):mat(matx.size(),std::vector<T>(matx[0].size))
{
for(int i=0;i<matx.size();i++)
{
for(int j=0;j<matx[0].size();j++)
{
mat[i][j] = matx[i][j];
}
}
}
};
template<typename T, typename X, typename Y>
class MatrixSum:public MatrixExpression<MatrixSum<T,X,Y>>
{
X const& x;
Y const& y;
public:
MatrixSum(X const& x1, Y const& y1):x(x1),y(y1){
assert(x1.size()==y1.size());
assert(x1[0].size()==y1[0].size());
}
class ProxySum
{
std::vector<T> vec1,vec2;
public:
ProxySum(std::vector<T> vec1,std::vector<T> vec2):vec1(vec1),vec2(vec2){ }
T operator[](std::size_t i){ return vec1[i] + vec2[i];}
//T &operator[](std::size_t i){ return vec1[i] + vec2[i];}
std::size_t size() const{ return vec1[0].size(); }
};
ProxySum operator[](std::size_t i) const { return ProxySum(x[i],y[i]); }
//ProxySum &operator[](std::size_t i){ return ProxySum(x[i],y[i]); }
size_t size() const { return x.size(); }
};
template<typename T,typename X,typename Y>
MatrixSum<T,X,Y>
operator+(X const& x, Y const& y)
{
return MatrixSum<T,X,Y>(x,y);
}
I am getting two errors when using the Matrix class. First is the operator+ does not exist for Matrix (I used int from testing) even though I have implemented operator overloading for '+', and another error is in the second constructor for Matrix. It says that the call I have made for the constructor of mat variable is invalid.But vectors do have such constructor
1) The following line is not a valid C++ syntax:
mat(m,std::vector<T>(n));
You should initialize mat member object in the constructor's initialization list, like this (assuming the outermost initializer_list is not empty):
Matrix(std::initializer_list<std::initializer_list<T>> lst) : mat(lst.size(), std::vector<T>(begin(lst)->size()))
2) As for the operator + you provided:
template<typename T,typename X,typename Y>
MatrixSum<T,X,Y>
operator+(X const& x, Y const& y)
{
return MatrixSum<T,X,Y>(x,y);
}
Note that T template parameter is non-deducible, so the compiler cannot figure it out and thus cannot use this operator. The only way to call it would be like this:
matrix1.operator +<some_type>(matrix2);
...which is probably not what you want.
The right way would be to try and compute T at compile-time, based on X and Y types, using some metaprogramming.
So I was Playing around with c++11 Varidiacs, and I wanted to create a thing called CallClass, basically a class that warps a function, for later call,when all variables are set(truly I have No Idea If It can Be Useful):
#include <tuple>
template <typename OBJ,typename F,typename... VARGS>
class CallClass
{
public:
CallClass(OBJ& object,F callFunction)
:_object(&object),_func(callFunction)
{ }
CallClass(const CallClass& other)
:_func_args(other._func_args)
,_object(other._object)
,_func(other._func)
{ }
template <size_t INDEX>
auto get(){ return std::get<INDEX>(_func_args); }
template <size_t INDEX,typename T>
void set(const T& val){ std::get<INDEX>(_func_args) = val; }
template <size_t INDEX,typename T>
void set(T&& val){ std::get<INDEX>(_func_args) = val; }
auto Call()
{
//throws segmentation Fault Here
return InnerCall<0>(_func_args);
}
virtual ~CallClass() {}
protected:
private:
std::tuple<VARGS...> _func_args;
OBJ* _object;
F _func;
template <size_t INDEX,typename... ARGS>
auto InnerCall(std::tuple<VARGS...>& tup,ARGS... args)
{
auto arg = std::get<INDEX>(tup);
return InnerCall<INDEX + 1>(tup,args...,arg);
}
template <size_t INDEX,VARGS...>
auto InnerCall(std::tuple<VARGS...>& tup,VARGS... args)
{
return (_object->*_func)(args...);
}
};
Now when I try to compile(compiling using IDE:code::blocks, configured to use MINGW On windows ), it prints Compiler:Segmentation Fault, anybody any Ideas?
Usage:
class obj{
public:
obj(int a)
:_a(a)
{ }
virtual ~obj() {}
int add(int b,int c){
return _a + b + c;
}
private:
int _a;
};
int main(){
obj ob(6);
CallClass<obj,decltype(obj::add),int,int> callAdd(ob,obj::add);
callAdd.set<0,int>(5);
callAdd.set<1,int>(7);
cout << "result is " << callAdd.Call() << endl;
return 0;
}
After a Bit of a search i stumbled upon a similar issue, in a way.
apparently the way I'm unpacking the tuple is an issue, so i decided to use a different approach as shown in: enter link description here
had to add a few changes to suit my needs:
changes:
namespace detail
{
template <typename OBJ,typename F, typename Tuple, bool Done, int Total, int... N>
struct call_impl
{
static auto call(OBJ& obj,F f, Tuple && t)
{
return call_impl<OBJ,F, Tuple, Total == 1 + sizeof...(N), Total, N..., sizeof...(N)>::call(obj,f, std::forward<Tuple>(t));
}
};
template <typename OBJ,typename F, typename Tuple, int Total, int... N>
struct call_impl<OBJ,F, Tuple, true, Total, N...>
{
static auto call(OBJ& obj,F f, Tuple && t)
{
return (obj.*f)(std::get<N>(std::forward<Tuple>(t))...);
}
};
}
// user invokes this
template <typename OBJ,typename F, typename Tuple>
auto call(OBJ& obj,F f, Tuple && t)
{
typedef typename std::decay<Tuple>::type ttype;
return detail::call_impl<OBJ,F, Tuple, 0 == std::tuple_size<ttype>::value, std::tuple_size<ttype>::value>::call(obj,f, std::forward<Tuple>(t));
}
and changed Call():
auto Call()
{
std::tuple<VARGS...> func_args = _func_args;
return call(*_object,_func, std::move(func_args));
}
I will probably make a few more changes, like passing the tuple as a reference, and making the structs a part of my class.
I just want to ask whether boost::bimap provides a method to find the relation in the bimap?
since I have a bimap with unordered_multiset at both side, I will need a function to check whether these is a relation between two objects.
I read some documentation but didnt find that.
class MyClass
{
std::string s1;
std::string s2;
bool operator == (MyClass const& myClass)
{
return (s1 == myClass.s1 && s2 == myClass.s2);
}
};
namespace std
{
template<>
struct hash<MyClass>
{
std::size_t operator()(const MyClass& myClass) const
{
std::size_t Seed = 0;
boost::hash_combine(Seed, myClass.s1);
boost::hash_combine(Seed, myClass.s2);
return Seed;
}
}
}
int main()
{
typedef boost::bimaps::bimap<boost::bimaps::unordered_multiset_of<client,std::hash<MyClass>, std::equal_to>, boost::bimaps::bimap<boost::bimaps::unordered_multiset_of<client,std::hash<MyClass>, std::equal_to>> MyBiMap;
MyBiMap MAP;
Map.value_type myRelation;
MAP.insert(myRelation(myClassObject1,myClassObject2));
MAP.insert(myRelation(myClassObject1,myClassObject4));
MAP.insert(myRelation(myClassObject3,myClassObject4));
MAP.insert(myRelation(myClassObject3,myClassObject6));
MAP.insert(myRelation(myClassObject5,myClassObject2));
// I want to check whether there is a relation between myClassObject1,myClassObject4
// for example MAP.find(myRelation(myClassObject1,myClassObject4)) returns the iterator
// and MAP.find(myRelation(myClassObject1,myClassObject6)) returns end();
}