Is it possible to use generic programming without templates? - c++

Say for example I have a function that returns a value from a 2-dimensional array:
float get_2d_noise(const point& p)
{
return map2D[p.x][p.y];
}
The point is a class that I've defined as part of my library:
struct point
{
int x;
int y;
}
Aside from doing this:
template<typename T>
float get_2d_noise(const T& p)
{
return noisemap[p.x][p.y];
}
Is it possible to get the same effect? I.e., create get_2d_noise in such a way that anything with an x and y member will work? (preferably catching errors at compile time, rather than runtime).

You may cheat with generic lambda (c++14), so you don't use explicitly template:
auto get_2d_noise = [&](const auto& p) -> float
{
return map2D[p.x][p.y];
};

You could write a macro that takes the name of the type as parameter and then creates the desired function. Something like
CREATE_2D_NOISE_FOR(someType)
that gets expanded to
float get_2d_noise(const someType& p) {
return noisemap[p.x][p.y];
}
However, this is highly not recommended, as you loose all the expressiveness of templates and gain all the problems that come with macros.

One possibility woud be to be syntactically explicit about what youw want to do. You could create an interface IPoint or similar (which in C++ can be done using an abstract class) where you define getters for your data members, say GetX and GetY; then you could formulate your function as follows.
float get_2d_noise(const IPoint& p)
{
return noisemap[p.GetX()][p.GetY()];
}
That way, you would not have to use generics; instead, you would use inheritance. However, any type you would like to use with get_2s_noise would have to be derived from IPoint (and implement the getters in a meaningful way), but that seems to be what you are looking for.

Is it possible to get the same effect? I.e., create get_2d_noise in such a way that anything with an x and y member will work? (preferably catching errors at compile time, rather than runtime).
This is literally the entire point of the existence of templates: they were created in order to support generic programming in C++. So no, there isn't another way to write templates in C++ outside of writing templates.

Related

Genericity VS Polymorphic data structures [duplicate]

I am trying to get my head around applying template programming (and at some future point, template metaprogramming) to real-world scenarios. One problem I am finding is that C++ Templates and Polymorphism don't always play together the way I want.
My question is if the way I'm trying to apply template programming is improper (and I should use plain old OOP) or if I'm still stuck in the OOP mindset.
In this particular case, I am trying to solve a problem using the strategy-pattern. I keep running into the problem where I end up wanting something to behave polymorphically which templates don't seem to support.
OOP Code using composition:
class Interpolator {
public:
Interpolator(ICacheStrategy* const c, IDataSource* const d);
Value GetValue(const double);
}
void main(...) {
Interpolator* i;
if (param == 1)
i = new Interpolator(new InMemoryStrategy(...), new TextFileDataSource(...));
else if (param == 2)
i = new Interpolator(new InMemoryStrategy(...), new OdbcDataSource(...));
else if (param == 3)
i = new Interpolator(new NoCachingStrategy(...), new RestDataSource(...));
while (run) {
double input = WaitForRequest();
SendRequest(i->GetValue(input));
}
}
Potential Template Version:
class Interpolator<class TCacheStrategy, class TDataSource> {
public:
Interpolator();
Value GetValue(const double); // may not be the best way but
void ConfigCache(const& ConfigObject); // just to illustrate Cache/DS
void ConfigDataSource(const& ConfigObject); // need to configured
}
//Possible way of doing main?
void main(...) {
if(param == 1)
DoIt(Interpolator<InMemoryStrategy, TextFileDataSource>(), c, d);
else if(param == 2)
DoIt(Interpolator<InMemoryStrategy, OdbcDataSource>(), c, d)
else if(param == 3)
DoIt(Interpolator<NoCachingStrategy, RestDataSource>(), c, d)
}
template<class T>
void DoIt(const T& t, ConfigObject c, ConfigObject d) {
t.ConfigCache(c);
t.ConfigDataSource(c);
while(run) {
double input = WaitForRequest();
SendRequest(t.GetValue(input));
}
}
When I try to convert the OOP implementation to a template-based implementation, the Interpolator code can be translated without a lot of pain. Basically, replace the "interfaces" with Template type parameters, and add a mechanism to either pass in an instance of Strategy/DataSource or configuration parameters.
But when I get down to the "main", it's not clear to me how that should be written to take advantage of templates in the style of template meta programming. I often want to use polymorphism, but it doesn't seem to play well with templates (at times, it feels like I need Java's type-erasure generics... ugh).
When I often find I want to do is have something like TemplateType<?, ?> x = new TemplateType<X, Y>() where x doesn't care what X, Y is.
In fact, this is often my problem when using templates.
Do I need to apply one more level of
templates?
Am I trying to use my shiny new power template wrench to
install a OOP nail into a PCI slot?
Or am I just thinking of this all
wrong when it comes to template
programming?
[Edit] A few folks have pointed out this is not actually template metaprogramming so I've reworded the question slightly. Perhaps that's part of the problem--I have yet grok what TMP really is.
Templates provide static polymorphism: you specify a template parameter at compile time implementing the strategy. They don't provide dynamic polymorphism, where you supply an object at runtime with virtual member functions that implement the strategy.
Your example template code will create three different classes, each of which contains all the Interpolator code, compiled using different template parameters and possibly inlining code from them. That probably isn't what you want from the POV of code size, although there's nothing categorically wrong with it. Supposing that you were optimising to avoid function call overhead, then it might be an improvement on dynamic polymorphism. More likely it's overkill. If you want to use the strategy pattern dynamically, then you don't need templates, just make virtual calls where relevant.
You can't have a variable of type MyTemplate<?> (except appearing in another template before it's instantiated). MyTemplate<X> and MyTemplate<Y> are completely unrelated classes (even if X and Y are related), which perhaps just so happen to have similar functions if they're instantiated from the same template (which they needn't be - one might be a specialisation). Even if they are, if the template parameter is involved in the signatures of any of the member functions, then those functions aren't the same, they just have the same names. So from the POV of dynamic polymorphism, instances of the same template are in the same position as any two classes - they can only play if you give them a common base class with some virtual member functions.
So, you could define a common base class:
class InterpolatorInterface {
public:
virtual Value GetValue(const double) = 0;
virtual void ConfigCache(const& ConfigObject) = 0;
virtual void ConfigDataSource(const& ConfigObject) = 0;
virtual ~InterpolatorInterface() {}
};
Then:
template <typename TCacheStrategy, typename TDataSource>
class Interpolator: public InterpolatorInterface {
...
};
Now you're using templates to create your different kinds of Interpolator according to what's known at compile time (so calls from the interpolator to the strategies are non-virtual), and you're using dynamic polymorphism to treat them the same even though you don't know until runtime which one you want (so calls from the client to the interpolator are virtual). You just have to remember that the two are pretty much completely independent techniques, and the decisions where to use each are pretty much unrelated.
Btw, this isn't template meta-programming, it's just using templates.
Edit. As for what TMP is, here's the canonical introductory example:
#include <iostream>
template<int N>
struct Factorial {
static const int value = N*Factorial<N-1>::value;
};
template<>
struct Factorial<0> {
static const int value = 1;
};
int main() {
std::cout << "12! = " << Factorial<12>::value << "\n";
}
Observe that 12! has been calculated by the compiler, and is a compile-time constant. This is exciting because it turns out that the C++ template system is a Turing-complete programming language, which the C preprocessor is not. Subject to resource limits, you can do arbitrary computations at compile time, avoiding runtime overhead in situations where you know the inputs at compile time. Templates can manipulate their template parameters like a functional language, and template parameters can be integers or types. Or functions, although those can't be "called" at compile time. Or other templates, although those can't be "returned" as static members of a struct.
I find templates and polymorphism work well toegther. In your example, if the client code doesn't care what template parameters Interpolator is using then introduce an abstract base class which the template sub-classes. E.g.:
class Interpolator
{
public:
virtual Value GetValue (const double) = 0;
};
template<class TCacheStrategy, class TDataSource>
class InterpolatorImpl : public Interpolator
{
public:
InterpolatorImpl ();
Value GetValue(const double);
};
void main()
{
int param = 1;
Interpolator* interpolator = 0;
if (param==1)
interpolator = new InterpolatorImpl<InMemoryStrategy,TextFileDataSource> ();
else if (param==2)
interpolator = new InterpolatorImpl<InMemoryStrategy,OdbcDataSource> ();
else if (param==3)
interpolator = new InterpolatorImpl<NoCachingStrategy,RestDataSource> ();
while (true)
{
double input = WaitForRequest();
SendRequest( interpolator->GetValue (input));
}
}
I use this idiom quite a lot. It quite nicely hides the templatey stuff from client code.
Note, i'm not sure this use of templates really classes as "meta-programming" though. I usually reserve that grandiose term for the use of more sophisticated compile-time template tricks, esp the use of conditionals, recursive defintions etc to effectively compute stuff at compile time.
Templates are sometimes called static (or compile-time) polymorphism, so yes, they can sometimes be used instead of OOP (dynamic) polymorphism. Of course, it requires the types to be determined at compile-time, rather than runtime, so it can't completely replace dynamic polymorphism.
When I often find I want to do is have something like TemplateType x = new TemplateType() where x doesn't care what X,Y is.
Yeah, that's not possible. You have to do something similar to what you have with the DoIt() function. Often, I think that ends up a cleaner solution anyway (you end up with smaller functions that do just one thing each -- usually a good thing). But if the types are only determined at runtime (as with i in the OOP version of your main function), then templates won't work.
But In this case, I think your template version solves the problem well, and is a nice solution in its own right. (Although as onebyone mentions, it does mean code gets instantiated for all three templates, which might in some cases be a problem)

C++ class function to get/set multiple members

Class classname
{
int member1;
int member2;
...
int membern;
public:
void setmember1(int);
void setmember2(int);
...
void setmembern(int);
void getmember1(int);
void getmember2(int);
...
void getmembern(int);
}
I know that I can define 2n class functions to get and set n specified member values in-place for the declarations above.
However, this seems needlessly tedious when n is large. Is there a good way to define one class function that takes an extra argument to set/get any member of the class?
EDIT:
Syntax errors aside, my rationale for large n is to preserve the scientific framework behind the class. For example, say the class is enzyme. So I'd prefer to keep its properties in the same place and not index by number unless absolutely necessary.
Set/get functions are public because they're called in a different class (that sets up a GUI).
And, no, not all the members are ints. I copy-pastaed for the sake of simplicity.
In real code you should not have classes with many data members, and certainly not individually settable and gettable ones.
You could achieve what you are asking for using an array:
class classname
{
public:
setMemberDangerously(size_t index, int value) { data[index] = value; }
setMember(size_t index, int value)
{
if (! index < size) throw std::out_of_range("Index out of bounds");
data[index] = value;
}
private:
int data[N];
};
But now your class looks like a collection, in which case you might as well use a standard library container.
Either:
Write a script to generate the methods
Put all those integers into an array and use one get/set with an index
EDIT
Besides your get should be
int getX() const;
EDIT
Thought of another two possibilities
Overload the [] operator
Inherit from std::vector
You can invent any tools to make your bad-designed classes "almost manageable". If it's hard to write getters/setters, don't do this. Your class must be refactored.
General solution here is to avoid big values of n
Design your classes to preserve single responsibility principle. Avoid god-classes.
I am no fun of setters/getters, although they are quite common in applications like a GUI. Anyhow, I have a generic solution that does require a library and is probably an overkill for this problem. Assume you have the following class
class A
{
char member1;
int member2;
double membern;
public:
void set_member1(char c) { member1 = c; }
void set_member2(int i) { member2 = i; }
void set_membern(double d) { membern = d; }
char get_member1() { return member1; }
int get_member2() { return member2; }
double get_membern() { return membern; }
};
You can then write
auto val = _('c', 42, 3.14);
auto set = _(&A::set_member1, &A::set_member2, &A::set_membern);
auto get = _(&A::get_member1, &A::get_member2, &A::get_membern);
A a;
(a ->* set)(val);
cout << (a ->* get)() << endl;
which prints
(c, 42, 3.14)
That is, you are working with tuples. Syntax _(...) represents a tuple; val is a tuple of values (possibly of different types) and set/get are tuples of pointers to members. Operator ->* in the syntax given above allows calling multiple member functions on a single object with multiple arguments, one argument per function. The result of the call to get is again a tuple of values.
For all this to work, you need library ivl that I am currently developing. The syntax above is just a small sample; the library is much more flexible, allowing to define functions or operators for scalars and then call them on tuples or arrays, in any combination. All C++ operators are overloaded to allow this kind of "vectorization". Operator ->* can also work with function objects apart from pointers to members, so that calls are inlined. It also allows the alternative syntax
a ->* set._(val);
cout << a ->* get._() << endl;
so that member functions bind with arguments first, before being applied to the object(s). Member functions can have as many arguments (of any type) as you like, but all should have the same number of arguments in a single call.
You touched an old problem with C++, which is very limited reflection functionality in the language. The discussion below is worth to look at in case you came from a language with reflection:
How can I add reflection to a C++ application?
As for a practical advice, all other answers given here make perfect sense.

What is a good design to use external class on member functions?

I have the following design problem and am seeking for the most elegant and even more important most efficient solution as this problem comes from a context where performance is an issue.
Simply spoken I have a class "Function_processor" that does some calculations for real functions (e.g. calculates the roots of a real function) and I have another class "A" that has different such functions and needs to use the Function_processor to perform calculations on them.
The Function_processor should be as generic as possible (e.g. do not provide interfaces for all sorts of different objects), but merely stick to its own task (do calculations for any functions).
#include "function_processor.h"
class A {
double a;
public:
A(double a) : a(a) {}
double function1(double x) {
return a*x;
}
double function2(double x){
return a*x*x;
}
double calculate_sth() {
Function_processor function_processor(3*a+1, 7);
return function_processor.do_sth(&function1);
}
};
class Function_processor {
double p1, p2;
public:
Function_processor(double parameter1, double parameter2);
double do_sth(double (*function)(double));
double do_sth_else(double (*function)(double));
};
Clearly I can not pass the member functions A::function1/2 as in the following example (I know that, but this is roughly what I would consider readable code).
Also I can not make function1/2 static because they use the non-static member a.
I am sure I could use sth like std::bind or templates (even though I have hardly any experience with these things) but then I am mostly concerned about the performance I would get.
What is the best (nice code and fast performance) solution to my problem ?
Thanks for your help !
This is not really the best way to do this, either from a pure OO point of view or a functional or procedural POV. First of all, your class A is really nothing more than a namespace that has to be instantiated. Personally, I'd just put its functions as free floating C-style ones - maybe in a namespace somewhere so that you get some kind of classification.
Here's how you'd do it in pure OO:
class Function
{
virtual double Execute(double value);
};
class Function1 : public Function
{
virtual double Execute(double value) { ... }
};
class FunctionProcessor
{
void Process(Function & f)
{
...
}
}
This way, you could instantiate Function1 and FunctionProcessor and send the Function1 object to the Process method. You could derive anything from Function and pass it to Process.
A similar, but more generic way to do it is to use templates:
template <class T>
class FunctionProcessor
{
void Process()
{
T & function;
...
}
}
You can pass anything at all as T, but in this case, T becomes a compile-time dependency, so you have to pass it in code. No dynamic stuff allowed here!
Here's another templated mechanism, this time using simple functions instead of classes:
template <class T>
void Process(T & function)
{
...
double v1 = function(x1);
double v2 = function(x2);
...
}
You can call this thing like this:
double function1(double val)
{
return blah;
}
struct function2
{
double operator()(double val) { return blah; }
};
// somewhere else
FunctionProcessor(function1);
FunctionProcessor(function2());
You can use this approach with anything that can be called with the right signature; simple functions, static methods in classes, functors (like struct function2 above), std::mem_fun objects, new-fangled c++11 lambdas,... And if you use functors, you can pass them parameters in the constructor, just like any object.
That last is probably what I'd do; it's the fastest, if you know what you're calling at compile time, and the simplest while reading the client code. If it has to be extremely loosely coupled for some reason, I'd go with the first class-based approach. I personally think that circumstance is quite rare, especially as you describe the problem.
If you still want to use your class A, make all the functions static if they don't need member access. Otherwise, look at std::mem_fun. I still discourage this approach.
If I understood correctly, what you're searching for seems to be pointer to member functions:
double do_sth(double (A::*function)(double));
For calling, you would however also need an object of class A. You could also pass that into function_processor in the constructor.
Not sure about the performance of this, though.

c++ wrap return type

I am wrapping a library which I did not write to make it more user friendly. There are a huge number of functions which are very basic so it's not ideal to have to wrap all of these when all that is really required is type conversion of the results.
A contrived example:
Say the library has a class QueryService, it has among others this method:
WeirdInt getId() const;
I'd like a standard int in my interface however, I can get an int out of WeirdInt no problem as I know how to do this. In this case lets say that WeirdInt has:
int getValue() const;
This is a very simple example, often the type conversion is more complicated and not always just a call to getValue().
There are literally hundreds of function calls that return types likes these and more are added all the time, so I'd like to try and reduce the burden on myself having to constantly add a bajillion methods every time the library does just to turn WeirdType into type.
I want to end up with a QueryServiceWrapper which has all the same functionality as QueryService, but where I've converted the types. Am I going to have to write an identically names method to wrap every method in QueryService? Or is there some magic I'm missing? There is a bit more to it as well, but not relevant to this question.
Thanks
The first approach I'd think is by trying with templates such that
you provide a standard implementation for all the wrapper types which have a trivial getValue() method
you specialize the template for all the others
Something like:
class WeirdInt
{
int v;
public:
WeirdInt(int v) : v(v) { }
int getValue() { return v; }
};
class ComplexInt
{
int v;
public:
ComplexInt(int v) : v(v) { }
int getValue() { return v; }
};
template<typename A, typename B>
A wrap(B type)
{
return type.getValue();
}
template<>
int wrap(ComplexInt type)
{
int v = type.getValue();
return v*2;
};
int x = wrap<int, WeirdInt>(WeirdInt(5));
int y = wrap<int, ComplexInt>(ComplexInt(10));
If the wrapper methods for QueryService have a simple pattern, you could also think of generating QueryServiceWrapper with some perl or python script, using some heuristics. Then you need to define some input parameters at most.
Even defining some macros would help in writing this wrapper class.
Briefly, If your aim is to encapsulate the functionality completely so that WeirdInt and QueryService are not exposed to the 'client' code such that you don't need to include any headers which declare them in the client code, then I doubt the approach you take will be able to benefit from any magic.
When I've done this before, my first step has been to use the pimpl idiom so that your header contains no implementation details as follows:
QueryServiceWrapper.h
class QueryServiceWrapperImpl;
class QueryServiceWrapper
{
public:
QueryServiceWrapper();
virtual ~QueryServiceWrapper();
int getId();
private:
QueryServiceWrapperImpl impl_;
};
and then in the definition, you can put the implementation details, safe in the knowledge that it will not leach out to any downstream code:
QueryServiceWrapper.cpp
struct QueryServiceWrapperImpl
{
public:
QueryService svc_;
};
// ...
int QueryServiceWrapper::getValue()
{
return impl_->svc_.getId().getValue();
}
Without knowing what different methods need to be employed to do the conversion, it's difficult add too much more here, but you could certainly use template functions to do conversion of the most popular types.
The downside here is that you'd have to implement everything yourself. This could be a double edged sword as it's then possible to implement only that functionality that you really need. There's generally no point in wrapping functionality that is never used.
I don't know of a 'silver bullet' that will implement the functions - or even empty wrappers on the functions. I've normally done this by a combination of shell scripts to either create the empty classes that I want or taking a copy of the header and using text manipulation using sed or Perl to change original types to the new types for the wrapper class.
It's tempting in these cases to use public inheritance to enable access to the base functions while allowing functions to be overridden. However, this is not applicable in your case as you want to change return types (not sufficient for an overload) and (presumably) you want to prevent exposure of the original Weird types.
The way forward here has to be to use aggregation although in such as case there is no way you can easily avoid re-implementing (some of) the interfaces unless you are prepared to automate the creation of the class (using code generation) to some extent.
more complex approach is to introduce a required number of facade classes over original QueryService, each of which has a limited set of functions for one particular query or query-type. I don't know that your particular QueryService do, so here is an imaginary example:
suppose the original class have a lot of weired methods worked with strange types
struct OriginQueryService
{
WeirdType1 query_for_smth(...);
WeirdType1 smth_related(...);
WeirdType2 another_query(...);
void smth_related_to_another_query(...);
// and so on (a lot of other function-members)
};
then you may write some facade classes like this:
struct QueryFacade
{
OriginQueryService& m_instance;
QueryFacade(OriginQueryService* qs) : m_instance(*qs) {}
// Wrap original query_for_smth(), possible w/ changed type of
// parameters (if you'd like to convert 'em from C++ native types to
// some WeirdTypeX)...
DesiredType1 query_for_smth(...);
// more wrappers related to this particular query/task
DesiredType1 smth_related(...);
};
struct AnotherQueryFacade
{
OriginQueryService& m_instance;
AnotherQueryFacade(OriginQueryService* qs) : m_instance(*qs) {}
DesiredType2 another_query(...);
void smth_related_to_another_query(...);
};
every method delegate call to m_instance and decorated w/ input/output types conversion in a way you want it. Types conversion can be implemented as #Jack describe in his post. Or you can provide a set of free functions in your namespace (like Desired fromWeird(const Weired&); and Weired toWeired(const Desired&);) which would be choosen by ADL, so if some new type arise, all that you have to do is to provide overloads for this 2 functions... such approach work quite well in boost::serialization.
Also you may provide a generic (template) version for that functions, which would call getValue() for example, in case if lot of your Weired types has such member.

Using a function or class in c++ for a simple task?

I want to write a utility in my program which can convert a string to int. I know that I could use atoi or strtol for it but I need some error handling on it. Which is the better way to do it? Should I create a simple global function, maybe only in a specific namespace, or create a class that have a member which can do it for me?
For eg.:
namespace utility{
int ConvertStrToInt(std::string* str, int& convertednum)
{
//do the conversion and error handling
return convertednum;
}
}
or
class Utility{
public:
static int ConvertStrToInt(std::string* str, int& convertednum)
{//do the conversion and error handling here}
}
Sorry if the question sounds a bit silly but I am in a team with 2 other guy and we think about this very differently. 1 says the class is for everything and make classes for everything, and I think that for such a simple problem a simple function is a good solution.
So which is the more efficient? When should I use a simple function and when is the point from where class is the good solution?
Thx for everyone!
The class Utility as you have written it down above somehow contradicts the idea behind object oriented programming, as the method neither uses nor depends on any members of the class. Classes should rather be objects that have certain properties and methods on these properties.
If it is useful to have state in your conversion, use a class. Preferably, a functor so you can pass an instance around as a callable entity. If there is no state, then use a function.
As an aside, your signature and return type should probably look like this:
int ConvertStrToInt(const std::string& str);
Edit concerning this particular example, the C++ standard library provides this functionality already, so you don't need to re-implement it.
namespace is the usual way to go about this.
The function in the class should be declared static anyway, and having a class just so you can group functions together isn't good practice.
Neither. Go for a function object (sometimes called a Functor).
struct str_to_int {
int operator()(const std::string& s) const { return 23; }
};
Why? This gives you the ability to add state if you need it. It works
with all standard algorithm facilities and every modern C++
library. You can make it a template function without your users every
noticing it.
Now you can do things like:
std::vector<std::string> strings;
std::vector<int> integers;
std::transform(begin(strings), end(strings),
std::back_inserter(integers), str_to_int());
Or someday turn your definition into:
struct str_to_int {
int operator()(const std::string& s) const { return 23; }
// ha
int operator()(const std::wstring& s) const { return 42; }
// haha!
int operator()(const char* x) const { return 42; }
};
and the above code will continue to work without a problem. This wont be the case for a free function.
Random Remark: Why would you pass a pointer to a string for
something like that?
I would normally just use a function. Putting it into a class is just
noise (or pseudo-OO, since the class doesn't have any real behavior on
its own).
There is one exception: functional template arguments to the STL are
generally more efficient if you use a class with an operator()(),
rather than a function. (If you use a functional object, the actual
function being called is a compile time constant, and can easily be
inlined. If you use a function, the template argument is the type of
the function, not the function itself, and inlining is less likely.)
Even in this case, however, I'd start with the function, and add the
functional object type if needed.