C++ metaprogramming,why and when should be used? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am reading Abrahams,Gurtovoy book about C++ metaprogramming. I must admit that I do not understand properly there explanation for using template metaprogramming. For example:
You want the code to be expressed in terms of the abstractions of the problem domain.
Or:
You would otherwise have to write a great deal of boilerplate implementation code.
Could someone elaborate on this?

I too use C++ for scientific computing and, yes, template meta-programming comes in very helpful. One use is to help with implementations of general purpose numerical methods. A typical example is std::sort, which is an abstraction of sorting in such a way that it works for whatever you want to sort.
Similarly, you may write, say, a templated spline interpolation that can interpolate y(x) for any type x that implements the concept of a scalar (orderable, operators + - *) and type y that is interpolateable (allows y+y, y-y, y*x). Once you have established such a template, you can use it to interpolate, say, some matrix type over a double (representing time, for instance) without any further adaptations: it just works immediately (the compiler must do some work, though).

You want the code to be expressed in terms of the abstractions of the problem domain.
Template Metaprogramming (TMP) can be used to separate and abstract different tasks in your code. For example, Boost.Serialization is implemented so as to be completely agnostic of your (the user's) code. You just have to provide a bit of glue, in the form of a serialize() member function, and Boost.Serialize will be able to work with your class seamlessly. And since this is all at compile-time, this flexibility does not come at any runtime cost (as opposed to polymorphism).
You would otherwise have to write a great deal of boilerplate implementation code.
TMP techniques can be used to generate code, and to efficiently factorize common code. For example, Boost.Intrusive lets you "import" behaviour in your classes (by various means, such as inheritance or type traits), and that is nothing else than generating code and injecting it into your class to transform it into, for example, a list node.

Related

C++ organize flow of functions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm writing a program for a microcontroller in C++, and I need to write a function to input some numbers trough a computer connected to it.
This function should perform many different and well-defined tasks, e.g.: obtain data (characters) from the computer, check if the characters are valid, transform the characters in actual numbers, and many others. Written as a single function it would be at least 500 lines long. So I'll write a group of shorter functions and one "main" function that calls the others in the only meaningful order. Those functions will never be called in the rest of the code (except of course the main function). One last thing - the functions need to pass each other quite a lot of variables.
What is the best way to organize those functions? My first tough was to create a class with only the "main" function in the public section and the other functions and the variables shared by different functions as private members, but I was wondering if this is good practice: I think it doesn't respect the C++ concept of "class"... for example to use this "group of functions" I would need to do something like that:
class GetNumbers {
public:
//using the constructor as what I called "main" function
GetNumbers(int arg1, char arg2) {
performFirstAction();
performSecondAction();
...
}
private:
performFirstAction() {...};
performSecondAction() {...};
...
bool aSharedVariable;
int anotherVariable;
...
};
And where I actually need to input those numbers from the computer:
GetNumbers thisMakesNoSenseInMyOpinion (x,y);
Making the "main" function a normal class method (and not the constructor) seems to be even worse:
GetNumbers howCanICallThis;
howCanICallThis.getNumbers(x,y);
...
//somewhere else in the same scope
howCanICallThis.getNumbers(r,s);
This is really a software design question. To be honest, unless you're sharing the component with a bunch of other people, I would really worry too much about how its encapsulated.
Many libraries (new and old) might make a family of functions that are to be used in a specific way. Sometimes they have a built in "state machine," but do not have a specific way of enforcing that the functions are used in a specific order. This is okay, as long as its well documented. A group of functions might be prefixed by the same word and packaged as a library if its to be re-usable, that way someone could link to your dll and include the appropriate headers.
https://en.wikipedia.org/wiki/Finite-state_machine
A finite-state machine (FSM) or finite-state automaton (FSA, plural: automata), finite automaton, or simply a state machine, is a mathematical model of computation.
Another way of organizing a set of computations is to package them up as a class, allow the contructor to accept the required input, and...
Kick off the required computation in the constructor
Kick off the computation after calling a public function like ->compute()
Making it into a functor (a class with an overloaded set of () operators)
Along with basically countless other options...
This has some benefit because if later you have multiple ways to compute results, you can replace it on the fly using something called the Strategy Pattern.
https://en.wikipedia.org/wiki/Strategy_pattern
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioural software design pattern that enables selecting an algorithm at runtime.
In the end, it doesn't matter which you use as long as you are consistent. If you are looking to make something more "idiomatic" in a given language, you really have to go out there and look at some code on the web to get a feel for how things are done. Different communities prefer different styles, which are all in the end subjective.

What kind of C++ template programming can be called "meta programming"? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Using what kind of template technical, could be called "meta programming"?
Is there a good definition of what's and what's NOT meta programming?
Does our C++11 STL contain a lot of meta programming?
Is "type_traits" meta programming"?
Thanks a lot.
Q1. Using what kind of template technical, could be called "meta programming"?
Template metaprogramming refers to use of templates and the compiler to perform some of the key elements of programming: Looping, if-else branching, C/C++ switch like branching, recursion, etc.
The first such meta program was used to generate the first few prime numbers as compiler error messages. See http://www.erwin-unruh.de/primorig.html
Q2. Is there a good definition of what's and what's NOT meta programming?
A good definition can be found at Wikipedia.
Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates include compile-time constants, data structures, and complete functions. The use of templates can be thought of as compile-time execution. The technique is used by a number of languages, the best-known being C++, but also Curl, D, and XL.
Q3. Does our C++11 STL contain a lot of meta programming?
Most likely but that's a guess. I haven't delved into any implementation of the standard library.
Q4. Is "type_traits" meta programming"?
Once again, I haven't delved into it but I imagine most of the functionality of "type_traits" is implemented using metaprogramming techniques.
"Metaprogramming" is used in informal speech to refer to a variety of programming techniques:
Information about types, i.e "type traits". This is the most straight forward type of meta, in that "meta" here means "about something"
(Ab)using the C preprocessor or templates. You are not really programming "in" C++ but rather a sublanguage. The IOCCC has plenty of examples of people using the C preprocessor to do various complete programs, like Towers of Hanoi and calculating prime numbers. The "classic" example of a template metaprogram is calculating fibonacci. In other words you are going "outside" the normal scope of C++ to create programs, which makes this usage similar to metagaming
Quines, creating programs that make programs that make programs, self-hosting compilers, etc. Here "meta" means "self-referential", like a fractal
Whether the standard library contains "metaprogramming" is implementation-defined. Some implementations go crazy with it, others don't.
There isn't really a good definition either, the word "meta" is ironically kind of fuzzy.

In order to be a C++ programmer, should I always std::vector instead of making my own linked list? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Right now I'm making a class called Stopwatch for a Windows phone app. I need a dynamic data to add laps like a stopwatch does. That is, if a user presses the lap button while the stopwatch is running, it adds a data structure
struct lap
{
unsigned double start;
unsigned double stop;
}
(defined as a private variable in my Stopwatch class) to the end of some sort of dynamic data structure that is saving all the laps.
Now, Bjarne Stroustrup himself says that we should always use std::vector over linked lists: https://www.youtube.com/watch?v=YQs6IC-vgmo. So the Lord of C++ tells me that I should have
std::vector<Stopwatch::lap> Laps;
as a private variable in my class. However, at the same time, I don't need anywhere near all the functionalities of an std::vector, since the only things I'll be using it for is iterating through the elements and using push_back(). Should I create another generic linked list class that is limited to the functionalities I need?
If you need a linked-list, you can use std::list. But linked lists are rarely the correct tool. Way overstressed in programming books and courses, in my opinion. The default choice for a dynamically resizable sequence container in C++ is std::vector. So use it. If you don't need the extra functionality, don't use it (the unneeded functionality). It costs you nothing. Don't waste your time implementing another redundant and buggy sequence container.
Not needing all the available functionality provided by a standard class is a poor reason to write your own. If everyone followed that logic, we'd have tonnes of non-standard classes which just provide subsets of the functionality of the standard classes.
Moreover, it is not trivial to write classes representing abstract data structures, and your own implementations are more likely to have bugs than the standard one, and will likely not be as optimised.
Finally, it is not a significant drain of resources to use classes which provide more functionality than you use. This functionality is primarily just method implementations, and they don't take up a lot of space in the grand scheme of things.
The std algorithms and containers use an efficient code base that is reusable and extensible. You should consider that other programmers should be able to understand your code simply and reuse or extend it. It is much more better to use std containers for regular usage. That's because most programmers are familiar with std and also most of the algorithms in std are very optimized and i doubt you can write something faster that std::sort.
Unless when performance demands are critical, or the container requirements are very specific, there may be no choice but to implement a container from scratch.

What are the benfits of inheritance over template based data structures? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'll get to the point and explain below.
What, if any, are the benefits of...
template<class T>
class myStack : public myList<T>...// my stack
over
template<class T, Container = deque<T> >
class stack...// C++ stack
Recently I was writing some code and was faced with an inheritance issue where I was exposing aspects of the base class that I would rather not. The specific example isn't important so I'll relate it to few semesters ago when I took a data structures class where we implemented our own list, stack, queue and others.
In this class we were to design a stack which was to inherit from a list. The problem with this was I was exposing public methods of the base that could potentially damage the stack's integrity. It may be that I'm a bit of a purist but having the insert() and remove() lying around in the stack was bothersome for me. I didn't have time to investigate it then but this time I thought I would consult the C++ standard to see how the stack was defined there. Low and behold I found the code above; it was an obvious solution that I overlooked.
Here's my view...
The C++ implementation is "better" because it allows the user the freedom to choose the underlying structure if desired and maintains a more pure stack in that it is clear only stack functionality available to the user and can be more guarded from unintended corruption. Are there more substantial, non-subjective reasoning behind the design choice, or inherit flaws in it?
The obvious benefit of mine is code re-use which is par for the course, I don't see that as an additional benefit the way I personally see the benefit of the freedom with the C++ implementation. I do see the over exposure (my words) of the base class as a con though. Are there more substantial, non-subjective reasoning behind the design choice, or inherit flaws in it?
Again, I'm not concerned with languages, I'm more concerned with weighing the pros/cons for my own designs.
C++ collections and Java collections are very different. Java collections have an obvious type hierarchy, whereas most C++ collection types do not extend any other class, and templates are extensively used to support multiple collection types.
Although I don't know for sure, I imagine that the Java library developers made Stack a subclass of Vector because a stack is a collection of elements in a well defined order, so acts like a list, and by subclassing Vector they could get most of the implementation of the stack for free. This also has the benefit that you can use stacks in places where you need a list or a vector, for example you could pass a stack to a function that takes a list and iterates over it. Of course, c++ stacks are not iterable, so there is (intentianal or not) a very different semantics between the two stacks.
Finally, for your own code, if you are considering whether B should inherit or contain A, first ask yourself if B is an A, or more specifically, if you would ever want to treat a B as an A by passing it to a function that expects an A, or returning it from a function that needs to return an A. If so you should use inheritance, otherwise you should probably use composition.
The Stack class, as well as Vector, are legacy containers. They are left-overs of JDK1.0, they are based on an older design of the utils library, and are inefficient because of synchronization.
The preferred implementation of Stack in Java is given by implementations of the Deque interface (mainly ArrayDeque and LinkedList). You get the difference: in C++ one says that an stack has a given implementation. In Java one declares a class implementing the desired interface:
class ArrayDeque<E> extends AbstractCollection<E>
implements Collection<E>, Deque<E>, Queue<E> //etc
When using such classes, always take the less specialized interface possible, for instance:
Deque<String> stack = new LinkedList<String>();

What is the best way to implement templates in a programming language? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm designing a high level, object oriented, garbage collected programming language, and I'm having a problem with how to do templates. I plan on creating a VM-type system, similar to .NET or JVM (but it will use LLVM under the hood). The problem is that I want to have powerful, C++-like templates, but with dynamic linking (so I could replace the template library without recompiling everything that uses it). I want to be able to compile a source file without having the definition of the templates. Code generation at JIT-time should be minimized.
Here are the options I'm thinking of:
Have the concept of a template library which is statically linked into each compilation unit. A template library would essentially be like an AST with blanks to be filled in when the template is instantiated. The problem with this is that if two files are compiled with different versions of the template library, they may be incompatible, or if the template library is buggy, everything will have to be recompiled. This is how C++ does it.
Have template libraries that are linked at JIT-time. This solves most of the problems but requires the IR to essentially be an AST. I would like the IR to be much lower level. This requires much more work for JIT-ing.
Have wimpy C#-like generics with only types as arguments. This is quite limiting, but allows simple code generation and dynamic linking.
Are there any other good ways I'm not thinking of? I'm leaning towards the first option, but I don't really like any of the options. What do you think is the best option?
I guess it depends on the amount of specialization you want, i.e. how powerful the compiler of templates has to be.
If you look at c++, the compiler can do all sorts of fancy stuff (like generate subclasses via recursion, probably compute a fractal inheritance graph as well as computing the numbers of Pi on the fly).
If you want that power, you probably need a powerful high-level JIT. FWIW, I think that would be cool. (Just include the full compiler in the runtime.)
Depends a bit on the rest of the language... if you have operator overloading, value types etc, then you are really complicating matters (and possibly missing out on great optimisation opportunities) by not going the C++ route: the code using the template would also have to be represented as an AST up to JIT time to allow maximum specialization.
Since C++ templates are essentially a form of macros, they allow much of all the bloat produced by duplication to be reduced before you get generate code.
Template types (at least in C++) tend to be the most core types that underly all other code, as such, if they change, assuming other code will still be compatible with it is not going to be true for all but the smallest changes.
What you're trying to achieve is nearly impossible. You have to leave pretty much all of the high level representation of your language for both the templates definitions and the code using those templates, and perform your JIT compilation from almost the level of slightly processed source code. If you're ok with that - you'd have to keep the rest of your compiler really trivial, and you won't be able to use any of the heavyweight LLVM optimisations. There are no other ways around, template metaprogramming relies on the availability of the high level information.
Think about how powerful are these templates going to be. You must remember that having a language that is compiled Just In Time, means that a lot of the heavy lifting will have to be done at load time and at run time. So, the more powerful you make your templates the less performance you will get from them.
If you are really going to that path, you may also include the compiler in the run time as Macke suggested. In fact there are plenty of languages that do this.
By doing this you are making your implementation of the language an "interpreted" or partially "interpreted" one. In those terms a template is just a fancy dress for match-replace-eval, and there is anything wrong with that, templates often work like that in dynamic languages. Just remember that at the end it will be Power vs Performance.
Note: when facing this kind of decisions it may be worth to step back a little. Identify the use cases and prioritize them, separate how to implement from the design so you can iterate the design without having the implementation be a cause of paralysis, yet still having it into consideration.
Each iteration you extend the design to cover more use cases while deciding what will be the best design. When you reach a design you like you can iterate then you can iterate on the implementation too. This methodology allows you to cover the more important cases first.
Yes, I'm suggesting an iterative incremental methodology. And I do this because this question is about the design of a language yet it seems much concerned about the implementation. It is necessary to keep the ideas grounded or you will end up in one of the extremes (too much powerful with pity performance or no templates at all for a high performance solution).