Make argument mandatory without relying on position - c++

Say a class Foo has two dependencies (Bar and Baz), and that it is an error to construct a Foo without providing both of them. Constructor injection makes it easy to guarantee at compile time that this is done:
class Foo
{
public:
Foo(const std::shared_ptr<Bar>& bar, const std::shared_ptr<Baz>& baz);
// (don't get hung up on the type of pointer used; it's for example only)
};
But let's say Foo also needs two doubles:
class Foo
{
public:
Foo(const std::shared_ptr<Bar>& bar, const std::shared_ptr<Baz>& baz,
double val1, double val2);
};
Now there is a problem; it would be really easy for the caller to accidentally transpose val1 and val2 and create a runtime bug. We can add a Params struct to allow named initialization and preclude this:
class Foo
{
public:
struct Params
{
std::shared_ptr<Bar> bar;
std::shared_ptr<Baz> baz;
double val1;
double val2
};
Foo(const Params& params);
};
// ...
std::shared_ptr<Foo> MakeDefaultFoo()
{
Foo::Params p;
p.bar = std::make_shared<Bar>();
p.baz = std::make_shared<Baz>();
p.val1 = 4.0;
p.val2 = 3.0;
return std::make_shared<Foo>(p);
}
But now we have the problem that the caller might forget to populate one of the fields in Params, which would not be detectable until runtime. struct initialization syntax or an initializer list would make it impossible to forget a field, but then we're back to relying on position!
Is there some trick that makes it possible to have the best of both worlds--compiler-enforced mandatory arguments that are assigned by name instead of position?

Just have a simple wrapper may work:
template <typename Tag, typename T>
struct Argument {
explicit Argument( const T &val );
T get() const;
};
class Foo {
public:
struct Val1Tag;
struct Val2Tag;
typedef Argument<Val1Tag,double> Val1;
typedef Argument<Val2Tag,double> Val2;
Foo( Val1 v1, Val2 v2 );
};
Foo foo( Foo::Val1( 1.0 ), Foo::Val2( 2.3 ) );
Now types are explicit and you cannot swap them without getting compiler error.

Very curious to see what cdhowie is tinkering with, but in the meantime, a simple wrapper with different types might solve some problems:
struct Val1 {
explicit Val1(double v) : v(v) { }
operator double() const { return v; }
double v;
};
// copy for Val2
class Foo
{
public:
Foo(const std::shared_ptr<Bar>& bar, const std::shared_ptr<Baz>& baz,
Val1 val1, Val2 val2);
};
This way you can't mix them up, since you'll have to construct a Foo like:
Foo foo(bar, baz, Val1{3.0}, Val2{7.0});
It's a bunch of extra typing to make sure the types are different, and you definitely have to make sure you make the constructor explicit (or it defeats the point), but it helps.

Something like this (untested)
template <typename tag, typename t>
struct param
{
explicit param(t vv)
: v(vv) {}
param(const param& p)
: v(p.v) {}
t v;
};
struct one{}; struct two {};
using paramone = param<one, double>;
using paramtwo = param<two, double>;
void somefunc (paramone p1, paramtwo p2)
{ ... };
void somefunc (paramtwo p2, paramone p1)
{ somefunc(p1, p2); }
// using it
somefunc (2, 3); // bad
somefunc (paramone(2), paramtwo(3)); // good
somefunc (paramtwo(3), paramone(2)); // also good

Related

Virtually turn vector of struct into vector of struct members

I have a function that takes a vector-like input. To simplify things, let's use this print_in_order function:
#include <iostream>
#include <vector>
template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
vectorlike const & printme) {
for (int i : order)
std::cout << printme[i] << std::endl;
}
int main() {
std::vector<int> printme = {100, 200, 300};
std::vector<int> order = {2,0,1};
print_in_order(order, printme);
}
Now I have a vector<Elem> and want to print a single integer member, Elem.a, for each Elem in the vector. I could do this by creating a new vector<int> (copying a for all Elems) and pass this to the print function - however, I feel like there must be a way to pass a "virtual" vector that, when operator[] is used on it, returns this only the member a. Note that I don't want to change the print_in_order function to access the member, it should remain general.
Is this possible, maybe with a lambda expression?
Full code below.
#include <iostream>
#include <vector>
struct Elem {
int a,b;
Elem(int a, int b) : a(a),b(b) {}
};
template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
vectorlike const & printme) {
for (int i : order)
std::cout << printme[i] << std::endl;
}
int main() {
std::vector<Elem> printme = {Elem(1,100), Elem(2,200), Elem(3,300)};
std::vector<int> order = {2,0,1};
// how to do this?
virtual_vector X(printme) // behaves like a std::vector<Elem.a>
print_in_order(order, X);
}
It's not really possible to directly do what you want. Instead you might want to take a hint from the standard algorithm library, for example std::for_each where you take an extra argument that is a function-like object that you call for each element. Then you could easily pass a lambda function that prints only the wanted element.
Perhaps something like
template<typename vectorlike, typename functionlike>
void print_in_order(std::vector<int> const & order,
vectorlike const & printme,
functionlike func) {
for (int i : order)
func(printme[i]);
}
Then call it like
print_in_order(order, printme, [](Elem const& elem) {
std::cout << elem.a;
});
Since C++ have function overloading you can still keep the old print_in_order function for plain vectors.
Using member pointers you can implement a proxy type that will allow you view a container of objects by substituting each object by one of it's members (see pointer to data member) or by one of it's getters (see pointer to member function). The first solution addresses only data members, the second accounts for both.
The container will necessarily need to know which container to use and which member to map, which will be provided at construction. The type of a pointer to member depends on the type of that member so it will have to be considered as an additional template argument.
template<class Container, class MemberPtr>
class virtual_vector
{
public:
virtual_vector(const Container & p_container, MemberPtr p_member_ptr) :
m_container(&p_container),
m_member(p_member_ptr)
{}
private:
const Container * m_container;
MemberPtr m_member;
};
Next, implement the operator[] operator, since you mentioned that it's how you wanted to access your elements. The syntax for dereferencing a member pointer can be surprising at first.
template<class Container, class MemberPtr>
class virtual_vector
{
public:
virtual_vector(const Container & p_container, MemberPtr p_member_ptr) :
m_container(&p_container),
m_member(p_member_ptr)
{}
// Dispatch to the right get method
auto operator[](const size_t p_index) const
{
return (*m_container)[p_index].*m_member;
}
private:
const Container * m_container;
MemberPtr m_member;
};
To use this implementation, you would write something like this :
int main() {
std::vector<Elem> printme = { Elem(1,100), Elem(2,200), Elem(3,300) };
std::vector<int> order = { 2,0,1 };
virtual_vector<decltype(printme), decltype(&Elem::a)> X(printme, &Elem::a);
print_in_order(order, X);
}
This is a bit cumbersome since there is no template argument deduction happening. So lets add a free function to deduce the template arguments.
template<class Container, class MemberPtr>
virtual_vector<Container, MemberPtr>
make_virtual_vector(const Container & p_container, MemberPtr p_member_ptr)
{
return{ p_container, p_member_ptr };
}
The usage becomes :
int main() {
std::vector<Elem> printme = { Elem(1,100), Elem(2,200), Elem(3,300) };
std::vector<int> order = { 2,0,1 };
auto X = make_virtual_vector(printme, &Elem::a);
print_in_order(order, X);
}
If you want to support member functions, it's a little bit more complicated. First, the syntax to dereference a data member pointer is slightly different from calling a function member pointer. You have to implement two versions of the operator[] and enable the correct one based on the member pointer type. Luckily the standard provides std::enable_if and std::is_member_function_pointer (both in the <type_trait> header) which allow us to do just that. The member function pointer requires you to specify the arguments to pass to the function (non in this case) and an extra set of parentheses around the expression that would evaluate to the function to call (everything before the list of arguments).
template<class Container, class MemberPtr>
class virtual_vector
{
public:
virtual_vector(const Container & p_container, MemberPtr p_member_ptr) :
m_container(&p_container),
m_member(p_member_ptr)
{}
// For mapping to a method
template<class T = MemberPtr>
auto operator[](std::enable_if_t<std::is_member_function_pointer<T>::value == true, const size_t> p_index) const
{
return ((*m_container)[p_index].*m_member)();
}
// For mapping to a member
template<class T = MemberPtr>
auto operator[](std::enable_if_t<std::is_member_function_pointer<T>::value == false, const size_t> p_index) const
{
return (*m_container)[p_index].*m_member;
}
private:
const Container * m_container;
MemberPtr m_member;
};
To test this, I've added a getter to the Elem class, for illustrative purposes.
struct Elem {
int a, b;
int foo() const { return a; }
Elem(int a, int b) : a(a), b(b) {}
};
And here is how it would be used :
int main() {
std::vector<Elem> printme = { Elem(1,100), Elem(2,200), Elem(3,300) };
std::vector<int> order = { 2,0,1 };
{ // print member
auto X = make_virtual_vector(printme, &Elem::a);
print_in_order(order, X);
}
{ // print method
auto X = make_virtual_vector(printme, &Elem::foo);
print_in_order(order, X);
}
}
You've got a choice of two data structures
struct Employee
{
std::string name;
double salary;
long payrollid;
};
std::vector<Employee> employees;
Or alternatively
struct Employees
{
std::vector<std::string> names;
std::vector<double> salaries;
std::vector<long> payrollids;
};
C++ is designed with the first option as the default. Other languages such as Javascript tend to encourage the second option.
If you want to find mean salary, option 2 is more convenient. If you want to sort the employees by salary, option 1 is easier to work with.
However you can use lamdas to partially interconvert between the two. The lambda is a trivial little function which takes an Employee and returns a salary for him - so effectively providing a flat vector of doubles we can take the mean of - or takes an index and an Employees and returns an employee, doing a little bit of trivial data reformatting.
template<class F>
struct index_fake_t{
F f;
decltype(auto) operator[](std::size_t i)const{
return f(i);
}
};
template<class F>
index_fake_t<F> index_fake( F f ){
return{std::move(f)};
}
template<class F>
auto reindexer(F f){
return [f=std::move(f)](auto&& v)mutable{
return index_fake([f=std::move(f),&v](auto i)->decltype(auto){
return v[f(i)];
});
};
}
template<class F>
auto indexer_mapper(F f){
return [f=std::move(f)](auto&& v)mutable{
return index_fake([f=std::move(f),&v](auto i)->decltype(auto){
return f(v[i]);
});
};
}
Now, print in order can be rewritten as:
template <typename vectorlike>
void print(vectorlike const & printme) {
for (auto&& x:printme)
std::cout << x << std::endl;
}
template <typename vectorlike>
void print_in_order(std::vector<int> const& reorder, vectorlike const & printme) {
print(reindexer([&](auto i){return reorder[i];})(printme));
}
and printing .a as:
print_in_order( reorder, indexer_mapper([](auto&&x){return x.a;})(printme) );
there may be some typos.

Constructor taking shared_ptr

I have situation like this
struct Foo
{
Foo(int x, int y) : x(x), y(y)
{
}
int x, y;
};
class Bar
{
public:
typedef std::shared_ptr<const Foo> ConstFooPtr;
typedef std::shared_ptr<Foo> FooPtr;
Bar(int index = 0, FooPtr ptr = FooPtr()) : index_(index), ptr_(ptr)
{
}
private:
ConstFooPtr ptr_;
int index_;
};
I want to produce Bar and 2 methods comes to my mind
Bar::FooPtr ptr(new Foo(1, 2)); //1
auto ptr2 = std::make_shared<Bar::FooPtr::element_type>(42, 13); //2
auto bar = Bar(0, ptr);
The first one is pretty general, because if I will change the type of FooPtr perhaps I will not have to chage this code. But it uses new which is bad I guess.
Second doesn't use new, but it assumes that it is shared_ptr which is not general also.
Is there any method to make it work and be general? Or maybe I should never take some ptrs in constructor?
(I store ptr to const Foo because I will make copies of Bar and change index_, but data in ptr_ will be the same - You can assume that Foo is something big with some containers)
Just roll your own version of make_shared and put it as a static member of Bar:
template<typename... Args>
static FooPtr make_shared_foo(Args... args)
{
return ::std::make_shared<Foo>(::std::forward<Args>(args)...);
}
This way you can make you pointer like so:
auto ptr3 = Bar::make_shared_foo(3,14159);
Of course, nothing prevents you from taking this to its ultimate version:
Bar(int index = 0) : index_(index), ptr_(FooPtr())
{ }
template<typename... Args>
Bar(int index, Args... args)
: index_(index)
, ptr_(new Foo(::std::forward<Args>(args)...))
{ }
Which just allows you to pass your arguments to the constructor to Bar which will then forward them to create a pointer to Foo for its own consumption.

Simple example with templates

This is a simple question, and I am sure that it has been answered before but I cannot seem to find a good answer.
I have a class, Point:
template<class T>
Point{
\\code
}
...and now I want a vector of Points, some of which have T as an integer which have T as a double. I want to write something like
template<class T>
std::vector<Point<T> > points;
But, alas, this doesn't compile with the error "expected primary-expression before 'template'". I haven't been able to fidget with this code to make it work. Also relevant is that points is in the main class, so I can't stick the template declaration outside the function.
If someone could direct me to a solution, I would be much obliged.
Thanks.
If your goal is to have a vector that holds both Point<int> and Point<double> you can use Boost Variant.
typedef boost::variant<Point<int>, Point<double> > VariantPoint;
Then:
std::vector<VariantPoint> my_vector;
my_vector.push_back(Point<int>(1, 0));
my_vector.push_back(Point<double>(1.5f, 2.0f));
Will work. Note that to inspect the elements afterwards, you probably will have to use the visitor pattern as documented here.
If your goal is to have distinct vector types that can only hold one type of Point, then you may use:
template<typename T> using PointVector = std::vector<Point<T>>; // C++11
// Now you can write:
PointVector<int> my_vector;
// Which is equivalent to:
std::vector<Point<int>> my_vector;
Or, if C++11 is not an option:
template<typename T> struct PointVector
{
typedef std::vector<Point<T> > Type;
}
Then:
PointVector<int>::Type my_vector;
To get a single kind of vector, I would use inheritance:
template <typename T>
struct PointVector : public std::vector< Point<T> >
{
};
Note, the inheritance is just a mechanism to achieve the equivalent of a template typedef. This means, PointVector should not contain any data members or virtual functions. However, #ereOn's suggestion is preferred, and is discussed in the answer to this question.
The old fashioned way to achieve a variant would be to use a union.
class IntOrDouble {
union {
int i;
double d;
};
bool is_int;
bool is_double;
public:
IntOrDouble () : is_int(false), is_double(false) {}
IntOrDouble (int x) : is_int(true), is_double(false) { i = x; }
IntOrDouble (double x) : is_int(false), is_double(true) { d = x; }
int operator = (int x) {
is_int = true;
is_double = false;
return i = x;
};
double operator = (double x) {
is_int = false;
is_double = true;
return d = x;
};
operator int () const {
if (is_int) return i;
if (is_double) return d;
return 0;
}
operator double () const {
if (is_double) return d;
if (is_int) return i;
return 0;
}
};
typedef std::vector< Point<IntOrDouble> > PointVector;
But it all seems a little over the top for this use case. I'd just use vectors of double all around, unless memory was really tight.

templated variable

I currently have the following non templated code:
class Vector{
public:
double data[3];
};
static Vector *myVariable;
void func() {
myVariable->data[0] = 0.;
}
int main() {
myVariable = new Vector();
func();
}
I then want to template the dimension :
template<int DIM> class Vector{
public:
double data[DIM];
};
static Vector<3>* myVariable;
void func() {
myVariable->data[0] = 0.;
}
int main() {
myVariable = new Vector<3>();
func();
}
But I finally want to template my variable as well, with the dimension :
template<int DIM> class Vector{
public:
double data[DIM];
};
template<int DIM> static Vector<DIM> *myVariable;
void func() {
myVariable->data[0] = 0.;
// or perform any other operation on myVariable
}
int main() {
int dim = 3;
if (dim==3)
myVariable = new Vector<3>();
else
myVariable = new Vector<4>();
func();
}
However, this last version of the code produces an error : this static variable cannot be templated ("C2998: Vector *myVariable cannot be a template definition").
How could I possibly correct this error without a complete redesign (like inheriting the templated Vector class from a non templated class, which would require more expensive calls to virtual methods , or manually creating several myVariables of different dimensions) ? Maybe I'm just tired and don't see an obvious answer :s
Edit: Note that this code is a minimal working code to show the error, but my actual implementation templates the dimension for a full computational geometry class, so I cannot just replace Vector by an array. I see that there doesn't seem to be a solution to my problem.
Thanks!
It's been a while, but I've used constants in the template declaration before. I eventually went another direction with what I was working on, so I don't know if it'll ultimately be your solution either. I think the problem here is that any templated variable must know its template argument at compile time.
In your example, Vector<3> and Vector<4> are different types, and cannot be assigned to the same variable. That's why template<int DIM> static Vector<DIM> *myVariable doesn't make any sense; it doesn't have a discernible type.
template<int DIM> static Vector<DIM> *myVariable;
This is not allowed by the language specification. End of the story.
And since I don't understand the purpose of your code, or what you want to achieve, I cannot suggest any better alternative than simply suggesting you to try using std::vector<T>. It's also because I don't know how much am I allowed to redesign your code, and the way you use it, to make your code work.
You can use std::array to template-ize the dimension but you can't cast the pointer of one dimension to the pointer of another.
I think I found!
template<int DIM> class Vector{
public:
double data[DIM];
};
static void *myVariable;
template<int DIM>
void func() {
((Vector<DIM>*)myVariable)->data[0] = 0.;
// or perform any other operation on myVariable
}
int main() {
int dim = 3;
if (dim==3)
{
myVariable = (void*) new Vector<3>();
func<3>();
}
else
{
myVariable = (void*) new Vector<4>();
func<4>();
}
}
Vector<3> and Vector<4> are entirely different types and have no formal relation to one another. The fact that they are superficially similar from your point of view doesn't matter.
If you want them to be equivalent up to a certain type, we have a name for that: interfaces
template <typename Scalar = float>
class BasicVector {
public:
typedef Scalar * iterator;
virtual ~ BasicVector () {}
virtual size_t size () const = 0;
virtual iterator begin () = 0;
virtual iterator end () = 0;
};
template <unsigned N, typename Scalar = float>
class Vector : public BasicVector <Scalar> {
Scalar m_elements [N];
public:
using Scalar :: iterator;
size_t size () const {return N;}
iterator begin () {return m_elements;}
iterator end () {return m_elements + N;}
};
int main () {
BasicVector * a;
a = new Vector <3>;
a = new Vector <4>;
}

Deriving different and incomparable types from int in C++

I know I cannot derive from an int and it is not even necessary, that was just one (non)solution that came to my mind for the problem below.
I have a pair (foo,bar) both of which are represented internally by an int but I want the typeof(foo) to be incomparable with the typeof(bar). This is mainly to prevent me from passing (foo,bar) to a function that expects (bar, foo). If I understand it correctly, typedef will not do this as it is only an alias. What would be the easiest way to do this. If I were to create two different classes for foo and bar it would be tedious to explicitly provide all the operators supported by int. I want to avoid that.
As an alternative to writing it yourself, you can use BOOST_STRONG_TYPEDEF macro available in boost/strong_typedef.hpp header.
// macro used to implement a strong typedef. strong typedef
// guarentees that two types are distinguised even though the
// share the same underlying implementation. typedef does not create
// a new type. BOOST_STRONG_TYPEDEF(T, D) creates a new type named D
// that operates as a type T.
So, e.g.
BOOST_STRONG_TYPEDEF(int, foo)
BOOST_STRONG_TYPEDEF(int, bar)
template <class Tag>
class Int
{
int i;
public:
Int(int i):i(i){} //implicit conversion from int
int value() const {return i;}
operator int() const {return i;} //implicit convertion to int
};
class foo_tag{};
class bar_tag{};
typedef Int<foo_tag> Foo;
typedef Int<bar_tag> Bar;
void f(Foo x, Bar y) {...}
int main()
{
Foo x = 4;
Bar y = 10;
f(x, y); // OK
f(y, x); // Error
}
You are correct, that you cannot do it with typedef. However, you can wrap them in a struct-enum pair or int encapsuled inside struct.
template<int N>
struct StrongType { // pseudo code
int i;
StrongType () {}
StrongType (const int i_) : i(i_) {}
operator int& () { return i; }
StrongType& operator = (const int i_) {
i = i_;
return *this;
}
//...
};
typedef StrongType<1> foo;
typedef StrontType<2> bar;
C++0x solution:
enum class foo {};
enum class bar {};