First of all, note that I'm using C++03 (and C++11 is not an option). I'm using boost concept to check that a certain class is default-constructible:
BOOST_CONCEPT_ASSERT((boost::DefaultConstructible<my_class>));
However, for some other class I'd like to assert that the type does not have a default constructor. Is there a way of doing this?
Update: to all those super-duper experts marking the question as duplicate or already answered without reading it: I state in the very first paragraph that I already use boost concept to check that classes are default-constructible (which is the question this is supposed to be a duplicate of). I also explicitly state that I can't use C++11, so type_traits are not available to me. So, could somebody please point me to the specific part where my question was "already answered"? Because I haven't found it yet.
The disappointing bit is that no, this is not possible with boost concept check.
The not so disappointing bit is: aren't you trying to use this tool backwards?
Generally, you write code that needs a type that has a certain number of features, such as constructors, functions that operate on that type, and so on.
I can't imagine a situation where you would write code that needs a type which lacks specific features.
You seem not to be wanting to do concept-oriented programming, but to enforce coding style.
And this is not the right tool for it.
Related
So C++20 Introduces a new thing called concept, which from what I see is used to constrain types of data that could be put into a template. So for a function, I could require that data that's fed in to like, must have a member ::inner, or something like that.
Which to me, it's like making sure whose using that function couldn't just put whatever they like into the argument. But doesn't explicit instantiation already doing the same stuff? Like if I wrote a function library, and I didn't directly wrote the implementation directly into header files, but rather wrote it in a separate .cpp file and also explicit instantiate them. Doesn't such approach defeats the usage of concept? As if me, the developer, is instantiate some data types to some function, I'm already guaranteeing that it'll work as expected when fed into the function's argument. And if I didn't instantiate a function for a class, then you simply couldn't call it.
In such case, is there any reason for me to implement concept? Except that it seems C++20's concept error is more clear than the error you'll receive without concept.
I'm setting aside the design choice of using templates only to explicitly instantiate everything. Maybe you need that maybe you don't, but concepts is a valuable tool regardless.
First of all a well defined concept will provide "in-code" documentation of what the characteristics of expected types are. If you instantiate something with int and Duck, it's not going to be clear what an int and a Duck have in common to be able to use the same template. Whereas if they were sharing for example the copyable concept it becomes apparent what instantiations have in common or why the generalization was made.
Secondly your library might need extensions (I mean if it's not dead code, it will need amending of some sort sooner or later). By expressing the type requirements, you communicate not only restrictions but intent as well; this is extremely valueable for code extensibility.
Lastly it makes your design process clear(er). If you're using templates in the first place, it is a good practice to be able to formally verify your type system, predict connections and dead ends and put some extra thought on what you actually want to generalize over. An amazing example of how concepts benefit this process, can be seen with named requirements. The Standards committee put a tremendous effort into formalizing the properties of types when defining standard library facilities so e.g. an algorithm may be defined on Containers of Trivially Copyable elements. Up until concepts, the burden of verifying and checking those types fell on the developer, since there was no formal way of expressing those requirements; now we're transitioning to concepts making the definition and checking of such properties a formal process, backed by the core language.
In support of the 2nd & 3rd points consider SFINAE techniques vs concepts. Using templates is much more than what you expose in an interface, so your library may internally rely on type restrictions to choose the correct compilation path. This process is cleanly defined with concepts, whereas legacy approaches tend to overcrowd your code.
is there any way to overload the "dot"-operator "."
We would like to use our old code base while rewriting the ORM layer. So we had the idea to wrap the objects and add some new semantic to the member selection operator "."
We found a several sites discussing that, including here on SO, all say in theory it would be fine but current C++ standard does not allow it.
Maybe there is already a compiler which does it?
EDIT
thanks for your quick answers; We see it might be hard if not impossible to find such a compiler. Any further hints are appreciated. All your posted resources we already had read...
Briefly what we want to achieve: The wrapper does not have any own members, it just should provide the former real object in another way. It would be very convenient to implement our new layer for reasons of backward compatibility - we could avoid to modify the legacy client code in about >4000 occurrences.
If you have any other idea how to proceed in another way, please tell. Will this limit be still there in C++11 ?
EDIT 2
Not sure yet, I am going to report what we do.
You can't overload the dot operator, and there is no c++ compiler that supports this property. Check this link from wikipedia which explains operator overloading in C++ in more detail. http://en.wikipedia.org/wiki/C%2B%2B_operators
Also on programmers.stackexchange.com:
I understand that STL concepts had to exist, and that it would be silly to call them "classes" or "interfaces" when in fact they're only documented (human) concepts and couldn't be translated into C++ code at the time, but when given the opportunity to extend the language to accomodate concepts, why didn't they simply modify the capabilities of classes and/or introduced interfaces?
Isn't a concept very similar to an interface (100% abstract class with no data)? By looking at it, it seems to me interfaces only lack support for axioms, but maybe axioms could be introduced into C++'s interfaces (considering an hypothetical adoption of interfaces in C++ to take over concepts), couldn't them? I think even auto concepts could easily be added to such a C++ interface (auto interface LessThanComparable, anyone?).
Isn't a concept_map very similar to the Adapter pattern? If all the methods are inline, the adapter essentially doesn't exist beyond compile time; the compiler simply replaces calls to the interface with the inlined versions, calling the target object directly during runtime.
I've heard of something called Static Object-Oriented Programming, which essentially means effectively reusing the concepts of object-orientation in generic programming, thus permitting usage of most of OOP's power without incurring execution overhead. Why wasn't this idea further considered?
I hope this is clear enough. I can rewrite this if you think I was not; just let me know.
There is a big difference between OOP and Generic Programming, Predestination.
In OOP, when you design the class, you had the interfaces you think will be useful. And it's done.
In Generic Programming, on the other hand, as long as the class conforms to a given set of requirements (mainly methods, but also inner constants or types), then it fits the bill and may be used. The Concept proposal is about formalizing this, so that detection may occur directly when checking the method signature, rather than when instantiating the method body. It also makes checking template methods more easily, since some methods can be rejected without any instantiation if the concepts do not match.
The advantage of Concepts is that you do not suffer from Predestination, you can pick a class from Library1, pick a method from Library2, and if it fits, you're gold (if it does not, you may be able to use a concept map). In OO, you are required to write a full-fledged Adapter, every time.
You are right that both seem similar. The difference is mainly about the time of binding (and the fact that Concept still have static dispatch instead of dynamic dispatch like with interfaces). Concepts are more open, thus easier to use.
Classes are a form of named conformance. You indicate that class Foo conforms with interface I by inheriting from I.
Concepts are a form of structural and/or runtime conformance. A class Foo does not need to state up front which concepts it conforms to.
The result is that named conformance reduces the ability to reuse classes in places that were not expected up front, even though they would be usable.
The concepts are in fact not part of C++, they are just concepts! In C++ there is no way to "define a concept". All you have is, templates and classes (STL being all template classes, as the name says: S tandard T emplate L ibrary).
If you mean C++0x and not C++ (in which case I suggest you change the tag), please read here:
http://en.wikipedia.org/wiki/Concepts_(C++)
Some parts I am going to copy-paste for you:
In the pending C++0x revision of the C++ programming language, concepts and the related notion of axioms were a proposed extension to C++'s template system, designed to improve compiler diagnostics and to allow programmers to codify in the program some formal properties of templates that they write. Incorporating these limited formal specifications into the program (in addition to improving code clarity) can guide some compiler optimizations, and can potentially help improve program reliability through the use of formal verification tools to check that the implementation and specification actually match.
In July 2009, the C++0x committee decided to remove concepts from the draft standard, as they are considered "not ready" for C++0x.
The primary motivation of the introduction of concepts is to improve the quality of compiler error messages.
So as you can see, concepts are not there to replace interfaces etc, they are just there to help the compiler optimize better and produce better errors.
While I agree with all the posted answers, they seem to have missed one point which is performance. Unlike interfaces, concepts are checked in compile-time and therefore don't require virtual function calls.
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 4 years ago.
Improve this question
As you may have heard, the last meeting of the C++ standards committee voted to remove concepts from the next C++ standard. Of course, this will affect other features and would seem to throw the standard wide open again. If that is the case, which other features do you think should be stripped away (or added), and why?
Links:
Removal of Concepts -- Danny Kalev (on the decision to remove concepts)
Simplifying the use of Concepts -- Bjarne Stroustrup (on the problems with concepts as they look now)
The Long Pole Gets Longer -- Martin Tasker (on the impact to the schedule for C++0x if concepts have to be fixed)
The C++0x "Remove Concepts" Decision - Stroustrup on the issue on Dr. Dobbs
Trip Report: Exit Concepts, Final ISO C++ Draft in ~18 Months - Herb Sutter
Concepts Get Voted Off The C++0x Island - Jeremy Siek defending the current Concepts spec
What Happened in Frankfurt? - Doug Gregor on C++Next (on the history and removal of Concepts).
Of course, this will affect other
features and would seem to throw the
standard wide open again.
Hardly. They still want to wrap up the standard soon, which is one of the main reasons for removing concepts. Making it "wide open" to unrelated changes would just throw away everything they gained by ditching concepts.
Anyway.... Of the remaining C++0x additions, I can't think of anything else I'd want to remove. I agree with their decision regarding concepts though. Stroustrup's paper really outlined some serious problems, The current specification for concepts would admittedly simplify template error messages, but it would do so by dramatically reducing the usefulness of generic programming -- a price I'm not willing to pay.
When I first read that paper, it scared me, because I assumed it was too late in the process for making serious changes to the spec. Turns out it wasn't, and the committee was willing to take dramatic action.
But apart from this, I think C++0x is in good shape. The remaining new features all look worthwhile.
Of course, there are plenty of existing features I'd love to remove. Primarily the vector<bool> specialization. There are other popular examples of features that didn't work out (the export keyword, exception specifications), but the vector specialization is the only one of them that can't be ignored. As long as we don't try to export templates, it doesn't matter that the keyword exists (and isn't implemented by compilers), and we can just refrain from using exception specs, but every time we need a vector of bools, we're bitten by the stupid premature optimization that slipped into the current standard.
Unfortunately, it seems like they've given up on removing it. (Last I checked, it wasn't even deprecated).
Of course, plenty of old C cruft could be ditched too, but recently, I've discovered that the one change I'd really love to see is...... ditching the Iostreams library. Toss it out, and build a new STL-style I/O library based on generic programming.
The current OOP-styled Iostreams library is ugly, slow, overcomplicated and inflexible. There's too much voodoo involved in defining new streams, too few standard stream types involved, too little flexibility (the problem that made me realize how limited the library is, was that I needed to extract a float from a string. Easy to do with stringstream, but if you need to do it often, you don't want to have to copy the input string every time (as the stringstream does) -- where's the stream that works on an existing iterator range? Or a raw array, even?)
Throw IOstreams out, develop a modern replacement, and C++ will be vastly improved.
And perhaps do something about the string class as well. It works sort of ok'ish as it is now, but really, what's with the huge number of member functions? Most of them would work better, and be more general, as free functions. Too much of the standard library relies specifically on the string class, when it could in principle work with any container, or even an iterator (std::getline, I'm looking at you)
Personally, I want C++ to finally break away from C. No more pre-processor, no more header files. I basically want D, but without all the stuff that D tacks on, using the STL.
None, I think the rest of the draft was great - a large number of very small pieces that can be correctly implemented independently, allowing vendors to evolve toward complete support and allowing users to take a "shopping list" approach.
Quite a different situation with contracts, as they were like a whole new parallel type system and would have been very likely to have led to different compilers ending up with their own backward compatibility problems, very similar to CSS in web browsers.
There are two things I think should be added to C++0x, I've thought of both these myself and then found that others have suggested them before but it doesn't seem like they're going to happen.
1. Defaulting Move Constructors and Move Assignment Operators
Writing a move constructor is a manual and error prone activity, if a member is added it must be added to the move constructor and assignment operators and std::move must be used religiously. That's why I think these functions should be defaultable.
movable(movable&&) = default;
movable& operator=(movable&&) = default;
Edit (2009-10-01): Looks like this is going to happen after all.
2. Override Type Deduction for Expression Templates
Expression templates often define types that should not be used directly, a case in point is the return value of std::vector<bool> operator[](size_type n), if auto or decltype are used on this kind of object unexpected behaviour may ensue.
Therefore a type should be able to say what type it should be deduced to be (or prevent deduction using = delete syntax).
Example for vector addition.
// lazy evaluation of vector addition
template<typename T, class V1, class V2>
class vector_add {
V1& lhs_;
V2& rhs_;
public:
T operator[](size_t n) const
{ return lhs_[n] + rhs_[n]; }
// If used by auto or decltype perform eager creation of vector
std::vector<T> operator auto() const
{
if (lhs_.size() != rhs_.size())
throw std::exception("Vectors aren't same size");
std::vector<T> vec;
vec.reserve(lhs_.size());
for (int i = 0; i < lhs_.size(); ++i)
vec.push_back(lhs_[i] + rhs_[i]);
return vec;
}
To me the problem is not what other features should be stripped away, but how complex will other features be after concepts have been removed. That and how much longer will it take for the rest of the features to be rephrased without concepts.
A lot of features assumed that concepts would be accepted into the language and the wording is expressed in terms of concepts. (I wonder if any proposed feature depends on concepts).
I also wonder how other libraries will evolve (think boost::type_traits) to take the niche left by concepts. Part of what concepts provided can be implemented (even if in a more cumbersome way) in terms of traits applied to the type arguments.
To me, the most important thing that concepts added to the language was an expressive formulation of compilation errors, which is nowadays one of the places where C++ is most criticized.
R.I.P. concepts.
Do whatever you want with concepts, but for god's sake keep threads and atomics, we absolutely need them. Perhaps add thread groups and support for cooperative threads a.k.a. fibers. IMO these are far more important than concepts, because everyone uses/will soon be using threads.
I'd like to remove =delete.
There's already a common and accepted idiom for acheiving the same effect (declare the function in question as private). I think this feature will just generate lots of 'I used =delete to remove a base class function from my derived class, but it can still be called using a base class pointer' questions.
Not to mention confusing people between the (now) two meanings of the delete keyword.
Strip away the pages of error messages on template code!
IIRC concepts should solve a big C++ coder problem: Human readable error messages for the STL. Its bad news that this issue isn't addressed.
The un-named function / lambda function stuff makes me nervous. Function objects are perfectly good and are explicit, thus easier to read and find.
On the other hand I kinda liked concepts, though I certainly would not have used them every day.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What are the coolest examples of metaprogramming that you've seen in C++?
What are some practical uses of metaprogramming that you've seen in C++?
Personally, I think Boost.Spirit is a pretty amazing example of meta-programming. It's a complete parser generator that lets you express grammars using C++ syntax.
The most practical use of meta programming is turning a runtime error into a compile time error.
Example: Lets call the interface IFoo. One of my programs dealt with a COM object that had multiple paths to IFoo (very complicated inheritance hierarchy). Unfortunately the underlying COM object implementation didn't realize they had multiple paths to IFoo. They assumed it was always the left most one. So inside their code, the following pattern was very common
void SomeMethod(IFoo* pFoo) {
CFooImpl *p = (CFooImpl)pFoo;
}
The second IFoo though caused the resulting "p" pointer to be completely invalid (multiple inheritance is dangerous).
The long term solution was to have the COM object owner fix this issue. Short term though I needed to make sure that I always returned the correct IFoo. I could guarantee that I had the appropriate IFoo by using a QI and avoiding any implicit casts to IFoo. So I created a new CComPtr<> implementation and added the following override to the equal method.
template <typename T>
CComPtr<T>& operator=(const T* pT) {
// CComPTr Assign logic
}
template <>
CComPtr<IFoo> operator=<IFoo>(const IFoo* pT) {
COMPILE_ERROR();
}
This quickly revealed every single place I implicitly casted to IFoo.
Not of practical usage (except maybe for compiler testing), but metatrace is a Whitted-Style (i.e. recursive and deterministic) ray tracer which generates images like those at compilation time:
Some more complex parts of the code can be seen in fixp.hh, which has an implementation of fixed-point sqrt using the Heron method, or sphere.hh which shows ray/sphere-intersection calculation.
Blitz++ does some impressive things with templates (for instance, a single readable line of code can be turned into a set of loops over a multidimensional array, automatically optimized for the best traversal order).
Coolest metaprogramming example: tricking the compiler into computing a list of prime numbers. Not very practical, but impressive.
One practical use is compile-time assert statements, i.e. causing a compile error if a Boolean condition does not hold.
Loki written by Andrei Alexandrescu
I would have to say Boost.Lambda, Boost.Function, and Boost.Bind and the way that they all work seamlessly together. They provide a really slick interface and make functional programming about as easy as possible in a language that wasn't really built for it.
luabind is a pretty cool practical example, quite a nice binding dsl for binding C++ classes to lua
BOOST_FOREACH
Static assertion (boosts version here)
(Note: builtin support for range-based for loops and static assertions is introduced in C++11)
I posed a question not to long ago: C++ Runtime Knowledge of Classes and the answer I got back from a StackOverflow user "Denice" was a URL to a website Meatspace: C++ runtime class registration.
I think that is a really cool way to use templates and instantiate objects that are all derived from a base class, so that when I have 10 C++ files, they can all just add the AUTO_REGISTER_BASE() at the bottom, and when everything is all done and linked, only those classes/files that made it would be registered, so at runtime you can switch between the different classes that are available, and those that are not available are not registered and thus can't accidently be called.
There are many different OS dependant ways to do event notification (select(), kqueue(), /dev/epoll, Solaris has it's own thing, poll()), and I needed a way to have all of the class files exist in the directory, but depending on what OS the Makefile was run, it would only compile certain ones. I needed a way to know at runtime which ones were available, and have a way for the programmer using the library to select their preference, however if it was unavailable to just use the one that made the most logical sense for the platform (they each have weights assigned to them).
The code above helped me accomplish this goal, with some hefty modifications, but it helped me none-the-less!