Does anybody know of any libraries that use design patterns that are implemented using compile-time techniques e.g. template metaprogramming? I know that Loki implements a few but I need to find other libraries.
Boost.Spirit is a pretty big one.
It depends on what design pattern you are interested in. There are some like "Active Object" and Dispose that would have a hard time being implemented at compile time.
"interpreter" pattern -> boost.ublas and blitz++ both use "expression templates"
"bridge" pattern -> Every standard container takes an "allocator" argument (most of Loki is bridge patterns as well)
"strategy" pattern -> STL template functions choose the best implementation based on the argument types
The only difference in all of these is that the evaluation of the pattern happens when the compiler runs, rather then when the executable runs. So all you need is to adjust your thinking slightly: The templates are the program, and the "C++ compiler" runs and interprets this program. The output of this template program is an object file ready for linking. In other words, your template code's runtime is precisley when your compiler is running. C++ templates are a turing complete functional language, just like lisp or XSLT.
In fact the very first template metaprogram in 1993 had as its output not an executable, but a series of compiler errors that printed the fibonacii sequence or something like that.
Some libraries that use expression templates: ublas, blitz, matrix template Library, ftensor, or Google C++ template matrix to find even more.
by the way, ftensor is really slick http://www.gps.caltech.edu/~walter/FTensor/FTensor.pdf.
I think that you are asking for libraries that help to use design pattern more that libraries using design patterns, isn't it?
There are some in Boost but not too much, like Flyweight - Design pattern to manage large quantities of highly redundant objects.
The not yet released but accepted library Boost.Factory and the rejected library Boost.Singleton
There are also some libraries that implements C++ idioms as Boost.Pimpl (on the review schedule), Scope Exit (accepted), Memoizer.
Doen almal GPG hier?
Any case those implemented in Loki:
- Factory Abstract
- Factory
- Singleton
- Visitor
- Command
In boost Flyweight
In STL you have iterators, and adapters, although I'm pretty sure they don't count
due to being being compile-time?
The original specification is somewhat vague.
Make sure that you do not confuse generic programming (template-based implementations) with other compile-time techniques.
Anyone have a clue as to what the above question means?
Related
I'm new to C++, and I have this question because I try to compare C++ to Java.
In Java, interface tell the developer which function to implement in order to use the Class or function I provide. For example, by specify the param type as Runnable, I tell the developer that the param I accepted need to have a run method, Iterable tells that the object need to have an iterator.
In C++, so far as I learned, I have encounter many cases that in compiling time, the compiler ask for some operator. And sometimes I even don't know how to specify the requirement of the param that others pass in.
To summarize my question, what's the general idea of approach when designing an template that I hope can handle more generic usage?
I know C++ is not an 100% object-orient language, so I'm still trying to get used to it, when shifting from Java.
AFAIK Java interfaces are for runtime polymorphism; in C++ they are plain classes that contain only pure virtual methods. Java needs a separate language entity for them as it supports only single inheritance for classes (which simplifies many corner cases) but allows multiple inheritance of interfaces; as C++ allows full multiple inheritance for classes in general, there's no need for this distinction.
OTOH, in C++ you don't use interfaces nearly as often - especially in the standard library, especially in the container part. Often compile-time polymorphism is used, in the form of templates.
Unfortunately as of today there's no way to express what operations should a type parameter of a template provide; the template-equivalent of interfaces - "concepts" - is being worked on by the C++ standard committee - unfortunately since many years now - and it's not ready yet.
For now you may only spell out your requirements in the documentation. If a type passed to the template doesn't satisfy them, you'll just get a compilation error pointing to the template code that tries to do something the type doesn't support. This leads to quite some confusion and horrible error messages, so you can try to mitigate this by strategically placing static_assert about the provided type checking if it conforms to what you need, thus providing better diagnostics in case of error.
Basis: i have very big parallel Fortran90/MPI program which represent complex physical model. I want to add new functionality to it: for example, i need to organize queue of messages, introduce mergesort somewhere and use hash tables.
Problem: i know how write hash table, create queue and code mergesort by my self, but i don't think it is a good idea to invent a bicycle.
Question: what Fortran guru should do in such situation? Should i build binds to C++ classes from Fortran and realize logic there using STL or you can suggest some Fortran STL-like libraries? Thank you.
There are no templates in Fortran and hence no STL. You can try FLIBS for some generic libraries. It generally uses transfer() tricks to achieve generic programming.
There is a preprocessor which adds some templates to Fortran and comes with some small STL, you can try that too named PyF95++. If you have access to academic papers through some library, you can read about it here.
I would avoid mixing it with C++ in this specific case although it can be done. You must instantiate each case separately and interface it to Fortran using a wrapper (bind(C) and iso_c_binding). Only if you have a very limited number of types you want to use the algorithms for it could be worth it.
You can also try to implement some poor-man's templates using the C-preprocessors in Fortran, For smaller libraries it works, but can become too difficult to maintain or ugly for complex things. As an example you can see my implementation of a linked list https://github.com/LadaF/fortran-list .
Generally, there is no clearly right approach or answer, you always have to choose from more possibilities.
In addition to everything that Vladimir F already mentioned, there is now also the Fortran Template Library (FTL). Much of the FTL is a reimplementation of C++'s STL in Fortran, where the C preprocessor is abused for template instantiation. You have to instatiate your templates manually, but otherwise it should be quite convenient from the end user perspective. The documentation can be found here.
The library is still fairly new and while it comes with a lot of unit tests, it hasn't seen much use in the wild yet. You'll also need a very recent Fortran compiler to use it.
Disclaimer: I am the author of this library.
I want to start this question by saying that it is paradigm-related and that I am only trying to clarify some concepts. So I have been programming in Python for about 2 years now, dipped my toes into Java but not too much and I want to delve into C++. I've used it before but not for large projects with a lot of design involved.
When I first started explored it I believed that it addressed OOP similarly to Java where everything has to implement an interface. Then I bumped into the concept of templates which I immediately though to be a workaround to provide polymorphic behaviour to primitives(ints, floats) which did not implement it(basically what Python did through duck-typing and no formal interfaces). But I soon discovered that templates were used to provide the same behaviour to non-primitive types.
So my question is: what reason is there to use classic polymorphism over templates, and what is the general approach to this in the C++ community?
EDIT Just found this which pretty much answers the question(static polymorphism really need to wrap my head around this terminology).
At the risk of making sweeping generalizations, templates are mostly used similarly to Generics in Java - they allow you to build a class or function that can be used with many different data types. Take std::list, part of the Standard Template Library. You can make a linked list of integers with std::list<int>, or a list of objects with std::list<MyClass>. Another example is std::thread, which uses templates to take a function (or lambda or functor) and its arguments to run in another thread.
As for choosing between a function f(SomeInterface x) and a function template f(T x), it really depends on context and is somewhat subjective. Some things to take into consideration are:
Function templates and class templates are resolved at compile time, so you may get better performance. However,
C++ compilers historically generate barely-descipherable garbage for template errors. Clang has done some work to improve this, and other compilers are getting better in an effort to match Clang. Things are getting better, but it's still pretty ugly.
Don't be afraid to use traditional polymorphism with interfaces and implementation classes. While templates are used instead of of polymorphism in some cases (see C++'s std::thread which uses templates vs. Java's Thread which uses a Runnable interface), polymorphism is still extremely common in C++ libraries and projects.
In short, feel free to consider using templates, but don't look at them as a replacement for polymorphism. Look at a popular C++ library and you're bound to find plenty of polymorphism. Take OGRE, a popular C++ graphics engine. If you look at its class list, you'll find lots of interfaces (such as WindowEventListener and FrameListener) which the user can derive a class from in order to interact with the library.
I would like to create a domain specific language as an augmented-C++ language. I will need mostly two types of contructs:
Top-level constructs for specialized types or declarations
In-code constructs, i.e. to add primitives to make functions calls or idiom easier
The language will be used for scientific computing purposes, and will ultimately be translated into plain C++. C++ has been chosen as it seems to offer a good compromise between: ease of use, efficiency and availability of a wide range of libraries.
A previous attempt using flex and bison failed due to the complexity of the C++ syntax. The existing parser can still fail on some constructs. So we want to start over, but on better bases.
Do you know about similar projects? And if you attempted to do so, what tools would you use? What would be the main pitfalls? Would you have recommendations in term of syntax?
There are many (clever) attempts to have domain specific languages within the C++ language.
It's usually called DSEL for Domain Specific Embedded Language. For example, you could look up the Boost.Spirit syntax, or Boost.rdb (in the boost vault).
Those are fully compliant C++ libraries which make use of C++ syntax.
If you want to hide some complexity, you might add in a few macros.
I would be happy to provide some examples if you gave us something to work with :)
You can try extending an open source Elsa C++ parser (it is now a part of a Mozilla's Pork project):
https://wiki.mozilla.org/Pork
The way to extend C++ is not to try to extend the language, which will be extremely difficult and probably break as new base compiler releases implement new features, but to write class libraries to support your problem domain. This has been what C++ programming has been all about since the language's inception.
If you really want to extend C++, you'll need a full C++ parser plus name and type resolution. As you've found out, this is pretty hard. Your best solution is to get an existing one and modify it.
Our DMS Software Reengineering Toolkit is an infrastructure for implementing langauge processors. It is
designed to support the construction of tools that parse languages, carry out transformations, and spit out the same language (with enhanced code) or a different language/dialect.
DMS has a full C++ Front End, that parses C++, builds abstract syntax trees and symbol tables (e.g., all that name and type resolution stuff).
The DMS/C++ front end is provided with DMS in source form, so that it can be customized to achieve the kind of effect you want. You'd define your DSL as an extension of the C++ front end, and then write transformations that convert your special constructs into "vanilla" C++ constructs, and then spit out compilable result.
DMS/C++ have been used for a wide variety of transformation tasks, including ones that involved extending C++ as you've described, and including tasks that carry out massive reorganizations of large C++ applications. (See the Publications at that website).
To solve you first bullet, maybe you can use C++0x new features "initializer lists", and "user defined litterals" avoiding the need for a new parser. They may help for the second bullet, too.
The Loki library implements some very widely used concepts (smart pointer, visitor, factory, etc.). The associated book "Modern C++ Design" is often mentioned, but the library itself is not widely used. Why is that?
Most developers seem to prefer Boost. In particular, why do people often decide to use Boost's smart pointers rather than Loki's?
Loki is a research/proof-of-concept sort of thing. Alexandrescu pushes new ideas, other people adopt those for real world. Also boost::shared_ptr is almost literally in TR1.
Loki's suffers from being a good library touching on several functional areas (template metaprogamming support with a few specific applications: smart pointers, singletons, function objects, scope guards etc.), whereas boost is a collection of many libraries typically exhaustively covering each functional area and much more highly tuned for portability (first).
When 9 birds out of 10 can be killed with the same stone, many people just start with boost and fill in the gaps with third party libraries. It's very hard to compete with boost if you overlap. Because you won't overlap with much of boost, people will download/install boost anyway to get the other functionality, so unless you nail an area that boost is weak at - and the difference is significant to the project, they'll "settle" for boost there too.
Further, Alexandrescu made repeated attempts to get Loki included in boost, and some of the key boost authors just weren't cooperative. My personal view is that they want the more complete but much less user-friendly MPL to have more "market share": as authors of the library and the hard-copy books that are the only decent documentation (in stark contrast with most other boost libraries which have excellent online documentation), they do quite well out of this.
If anyone is offended by and disagrees with this analysis, I'm all ears.
Another practical issue with extremely parameterised code is that in large projects where different developers/teams work independently, they'll often end up using subtly different instantiations of the same template pretty arbitrarily. This makes it harder to pass values between those subsystems: the receiver may need to:
be parameterised (i.e. templated, and hence inline, which introduces compilation dependencies and slower builds in enterprise-scale systems)
provide some minimal coverage for all possible instantiations (e.g. checking error codes and expecting/handling exceptions)
working through some compile-time to run-time hand-over based on an abstract base accessor with implementations for each instantiation) which compromises some of the performance benefits of parameterisation
This is all possible, but it takes a great programmer to navigate the terrain.
You want to use a library that the next programmer is going to know and that is going to be well supported in the future - so you pick a major lib.
Because it's a major lib lots of people use it, so it becomes the default choice.
I actually prefer Loki's way of doing things and I have contributed to Loki myself a Decorator pattern which now sits in the tracker because the project as far as I know is no longer maintained.
I use boost shared_pointer just because it will be the standard very soon, I may dislike the fact that I can't customize it to act exactly the way I want it to act but I have to live with it.
Usage of the standard library is important as it keeps the code maintainable by other programmers. If it's open source and you want to experiment go ahead and use Loki. No one is stopping you.
Actually Windows Vista uses some of Loki's features.
I am guessing they are not using the redundant implementations of smart pointers and visitors.
Speaking as someone who's used quite a bit of the Boost library, and also looked at Loki more than once, the biggest problem was the sparsity of documentation. Also, Loki uses some of the hairiest bits of C++ templates. Exciting stuff, but also rather daunting.
I used Loki once for a little tool (basically an interpreter) and actually liked it. My coworkers were less enthusiastic about the library, so its use remained constrained to this small sub-project.