power(C++ - {templates}) = power(C++)? - c++

I want to know whether it is possible to do generic programming in C++ without using templates. Is it possible to write all libraries available in C++ which are written using templates without using templates. Is there any alternative available in C++ for templates?
I want to know Is it possible to write an abstraction over libraries written in C++ using templates which provide me with the same functionality

Theoretically, C++ without templates is still Turing-complete, so you can write a program for every function in that language that can also be written in C++ with templates. To my knowledge, the macro preprocessor in C++ is not Turing-complete, but templates are. So there must exist functions which can be implemented purely as templates, but not with macros.
Practically, I don't think it is possible to re-implement everything with the same semantics. Without templates, you probably will have to sacrifice type-safety and stick to using macros, void* or inheritance-based approaches like the early Java classes did even for simple container libraries.
For more advanced meta-programming libraries, e.g. expression templates, dimensional analysis frameworks, Boost.Spirit Boost.Proto, I doubt that they can be implemented without another form of meta-programming. Macros may work, but this will be more like a code-generator and defer type-checking to the compiler and error messages will be even worse than what we have right now with templates. In addition, the semantics are different w.r.t parameter passing.

Well, templates are just that — templates. They are blueprints for actual types and functions. So, theoretically, you can make all of those template instantiations by hand. But that wouldn't be generic programming any more.

Answer for question:
Is there any alternative available in C++ for templates?
Macroses is alternative of templates. (Not good alternative, but alternative)
Related links [1],[2]
Compare:
#define min(i, j) (((i) < (j)) ? (i) : (j))
template<class T> T min (T i, T j) { return ((i < j) ? i : j) }
Problems of macroses:
no type checking,
not so understandable compiler errors becouse macroses expanding
sideffects of multiple computing expressions
About question:
Is it possible to write all libraries available in C++ which are written using templates without using templates.
It is possible to use macroses in some cases. It is possible to write or generate implementation for each library type. But for user defined type library can not have implementation, except simple cases when macroses may be useful.
Earlier pure C (not C++) programs have contain special tools in sources that was used at build stage to generate some sources from some "presource" templates.

Related

Recommended way to have backward compatible concepts in C++20

I'm fairly new to concepts but I like them so far and wanted to use them in a project. The problem is I also wanted the project to compile with earlier C++ standards. So far I've come up with the following pragmatized solution:
#if ISCPP20
template<NumT number = double,Index index = int,CoordinateContainer<number> coords>
#else
template<class number = double,class index = int,class coords>
#endif
where NumT, Index, and CoodinateContainer are defined concepts. The solution works but I don't like the verbosity. Is there a recommended method to introduce concepts into a codebase while not breaking backward compilation compatibility?
As a practical matter, if you want to be able to easily remove concepts from code with a macro check, you should not use any kind of compact concept syntax. That means you should always use explicit requires clauses. This makes the syntax easier to #if around.
If you have overloaded concepts, where multiple definitions exist with more restrictive concepts, that's not something that is easy to just remove. It's a part of your interface that you can pass types with different interfaces and the compiler picks which template gets instantiated through a complex overloading scheme.
So you'll have to use some form of SFINAE to do the equivalent. But exactly what you have to do depends on exactly how you're doing it. In some cases, it can be easy, such as with simple template functions that you might be able to convert to just if constexpr blocks inside a single definition.
But other cases are much more difficult. You can put requires clauses on non-template members of a template class. Doing an equivalent thing with SFINAE is much more difficult.
So how to get the same effect will depend on exactly what effect you're trying to achieve.

C++ should I use templates, I'm about to create a lexer, why should it be limited chars? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm about to create a lexer for a project, proof of concepts of it exists, the idea works and whatnot, I was about to start writing it and I realised:
Why chars?
(I'm moving away from C, I'm still fairly suspicious of the standard libraries, I felt it easier to deal in char* for offsets and such than learn about strings)
why not w_char or something, ints, or indeed any type (given it has some defined operations).
So should I use a template? So far it seems like yes I should but there are 2 counter-arguments I can consider:
Firstly, modular complication, the moment I write "template" it must go in a header file / be available with implementation to whatever uses it (it's not a matter of hiding source code I don't mind the having to show code part, it will be free (as in freedom) software) this means extra parsing and things like that.
My C background screams not to do this, I seem to want separate .o files, I understand why I can't by the way, I'm not asking for a way.
Separate object files speed up complication, because the make file (you tell it or have it use -MM with the compiler to figure out for itself) wont run the complication command for things that haven't changed and so forth.
Secondly, with templates, I know of no way to specify what a type must do, other than have the user realise when something fails (you know how Java has an extends keyword) I suspect that C++11 builds on this, as meta-programming is a large chapter in "The C++ programming language" 4th edition.
Are these reasons important these days? I learned with the following burned into my mind:
"You are not creating one huge code file that gets compiled, you create little ones that are linked" and templates seem to go against this.
I'm sure G++ parses very quickly, but it also optimises, if it spends a lot of time optimising one file, it'll re-do that optimisation every time it sees that in a translation unit, where as with separate object files, it does a bit (general optimisations) only once, and perhaps a bit more if you use LTO (link time optimisation)
Or I could create a class that every input to the lexer derives from and use that (generic programming I believe it's called) but my C-roots say "eww virtuals" and urge me towards the char*
I understand this is quite open, I just don't know where to draw the line between using a template, and not using a template.
Templates don't have to be in the header! If you have only a few instantiations, you can explicitly instantiate the class and function templates in suitable translation units. That is, a template would be split into three parts:
A header declaring the templates.
A header including the first and implementing the template but otherwise only included in the third set of files.
Source files including the headers in 2. and explicitly instantiating the templates with the corresponding types.
Users of these template would only include the header and never the implementation header. An example where this can be done are IOStreams: There are basically just two instantiations: one for char and one for wchar_t. Yes, you can instantiate the streams for other types but I doubt that anybody would do so (I'm sometimes questioning if anybody uses stream with a different character type than char but probably people are).
That said, the concepts used by templates are, indeed, not explicitly represented in the source and C++11 doesn't add any facilities to do so either. There were discussions on adding concepts to C++ but so far they are not part of any standard. There is a concepts light proposal which, I think, will be included in C++14.
However, in practice I haven't found that much of a problem: it is quite possible to document the concepts and use things like static_assert() to potentially produce nicer error messages. The problem is more that many concepts are actually more restrictive than the underlying algorithms and that the extra slack is sometimes quite useful.
Here is a brief and somewhat made-up example of how to implement and instantiate the template. The idea is to implement something like std::basic_ostream but merely provide out scaled-down version of a string output operator:
// simple-ostream.hpp
#include "simple-streambuf.hpp"
template <typename CT>
class simple_ostream {
simple_streambuf<CT>* d_sbuf;
public:
simple_ostream(simple_streambuf<CT>* sbuf);
simple_streambuf<CT>* rdbuf() { return this->d_sbuf; } // should be inline
};
template <typename CT>
simple_ostream<CT>& operator<< (simple_ostream<CT>&, CT const*);
Except for the rdbuf() member the above is merely a class definition with a few member declarations and a function declaration. The rdbuf() function is implemented directly to show that you can mix&match the visible implementation where performance is necessary with external implementation where decoupling is more important. The used class template simple_streambuf is thought to be similar to std::basic_streambuf and, at least, declared in the header "simple-streambuf.hpp".
// simple-ostream.tpp
// the implementation, only included to create explicit instantiations
#include "simple-ostream.hpp"
template <typename CT>
simple_ostream<CT>::simple_ostream(simple_streambuf<CT>* sbuf): d_sbuf(sbuf) {}
template <typename CT>
simple_ostream<CT>& operator<< (simple_ostream<CT>& out, CT const* str) {
for (; *str; ++str) {
out.rdbuf()->sputc(*str);
}
return out;
}
This implementation header is only included when explicitly instantiating the class and function templates. For example, to instantiations for char would look like this:
// simple-ostream-char.cpp
#include "simple-ostream.tpp"
// instantiate all class members for simple_ostream<char>:
template class simple_ostream<char>;
// instantiate the free-standing operator
template simple_ostream<char>& operator<< <char>(simple_ostream<char>&, char const*);
Any use of the simple_ostream<CT> would just include simple-ostream.hpp. For example:
// use-simple-ostream.cpp
#include "simple-ostream.hpp"
int main()
{
simple_streambuf<char> sbuf;
simple_ostream<char> out(&sbuf);
out << "hello, world\n";
}
Of course, to build an executable you will need both use-simple-ostream.o and simple-ostream-char.o but assuming the template instantiations are part of a library this isn't really adding any complexity. The only real headache is when a user wants to use the class template with unexpected instantiations, say, char16_t, but only char and wchar_t are provided: In this case the user would need to explicitly create the instantiations or, if necessary, include the implementation header.
In case you want to try the example out, below is a somewhat simple-minded and sloppy (because being header-only) implementation of simple-streambuf<CT>:
#ifndef INCLUDED_SIMPLE_STREAMBUF
#define INCLUDED_SIMPLE_STREAMBUF
#include <iostream>
template <typename CT> struct stream;
template <>
struct stream<char> {
static std::ostream& get() { return std::cout; }
};
template <>
struct stream<wchar_t> {
static std::wostream& get() { return std::wcout; }
};
template <typename CT>
struct simple_streambuf
{
void sputc(CT c) {
stream<CT>::get().rdbuf()->sputc(c);
}
};
#endif
Yes, it should be limited to chars. Why ? Because you're asking...
I have little experience with templates, but when I used templates the necessity arose naturally, I didn't need to try to use templates.
My 2 cents, FWIW.
1: Firstly, modular complication, the moment I write "template" it must go in a header file…
That's not a real argument. You have the ability to use C, C++, structs, classes, templates, classes with virtual functions, and all the other benefits of a multi paradigm language. You're not coerced to take an all-or-nothing approach with your designs, and you can mix and match these functionalities based on your design's needs. So you can use templates where they are an appropriate tool, and other constructs where templates are not ideal. It's hard to know when that will be, until after you have had experience using them all. Template/header-only libraries are popular, but one of the reasons the approach is used is that they simplify linking and the build process, and can reduce dependencies if designed well. If they are designed poorly, then yes, they can result in an explosion in compile times. That's not the language's fault -- it's the implementor's design.
Heck, you could even put your implementations behind C opaque types and use templates for everything, keeping the core template code visible to exactly one translation.
2: Secondly, with templates, I know of no way to specify what a type must do…
That is generally regarded as a feature. Instantiation can result in further instantiations which is capable of instantiating different implementations and specializations -- this is template meta programming domain. Often, all you really need to do is instantiate the implementation, which results in evaluation of the type and parameters. This -- simulation of "concepts" and interface verification -- can increase your build times, however. But furthermore, that may not be the best design because deferring instantiation is in many cases preferable.
If you just need to brute-force instantiate all your variants, one approach would be to create a separate translation which does just that -- you don't even need to link it to your library; add it to a unit test or some separate target. That way, you could validate instantiation and functionalities are correct without significant impact to your clients including/linking to the library.
Are these reasons important these days?
No. Build times are of course very important, but I think you just need to learn the right tool to use, and when and why some implementations must be abstracted (or put behind compilation firewalls) when/if you need fast builds and scalability for large projects. So yes, they are important, but a good design can strike a good balance between versatility and build times. Also remember that template metaprogramming is capable of moving a significant amount of program validation from runtime to compile time. So a hit on compile times does not have to be bad, because it can save you from a lot of runtime validations/issues.
I'm sure G++ parses very quickly, but it also optimises, if it spends a lot of time optimising one file, it'll re-do that optimisation every time it sees that in a translation unit…
Right; That redundancy can kill fast build times.
where as with separate object files, it does a bit (general optimisations) only once, and perhaps a bit more if you use LTO (link time optimisation) … Separate object files speed up complication, because the make file (you tell it or have it use -MM with the compiler to figure out for itself) wont run the complication command for things that haven't changed and so forth.
Not necessarily so. First, many object files produce a lot of demand on the linker. Second, it multiplies the work because you have more translations, so reducing object files is a good thing. This really depends on the structure of your libraries and dependencies. Some teams take the approach the opposite direction (I do quite regularly), and use an approach which produces few object files. This can make your builds many times faster with complex projects because you eliminate redundant work for the compiler and linker. For best results, you need a good understanding of the process and your dependencies. In large projects, translation/object reductions can result in builds which are many times faster. This is often referred to as a "Unity Build". Large Scale C++ Design by John Lakos is a great read on dependencies and C++ project structures, although it's rather dated at this point so you should not take every bit of advice at face value.
So the short answer is: Use the best tool for the problem at hand -- a good designer will use many available tools. You're far from exhausting the capabilities of the tools and build systems. A good understanding of these subjects will take years.

Is there a good/widely adopted c++ template coding convention/standards?

I like coding standards. When writing C++ I love coding standards. A good coding standard adds context to the language, making the hard to parse a little bit easier.
There are a few commonly practiced standards that I think everyone is at least a little bit familiar with:
Member variables prefixed with 'm' or 'm_'
Class prefix (generally project specific, ie in Qt all class names are prefixed with 'Q')
Include guard conventions like "take the filename in all caps, replace '.' with '_' "
The rule of three
There are lots of little C++ rules like this. Unfortunately I've never managed to find guidelines like this relating to templates. I think the most popular name for a template argument is 'T', but it's meaningless and unless the template is obvious it can make the code even trickier to read.
Anyway, the core problem I have is that templates are hard to read and I think some convention could be used to make them easier to read. Does anyone know of a widely applied convention that makes templatized code easier to read?
Just adding my grain of salt. I think the two most important libraries in the world of C++ programming are the Standard Template Libraries and the Boost Libraries. I personally try to mostly conform to the kind of notation that is predominant in these libraries. That is, underscore-separated lower-case names for classes, functions, data members, typedefs, enums, etc., and CamelCase (no underscore separation) for template arguments. Typically, you want to also have sensible names for template arguments. A good practice is to give them the name of the concept they should be implementing (e.g. a template argument which should be an iterator that implements ForwardIteratorConcept should be named ForwardIterator).
The conventions that you mentioned ("m" for members and Capital-letter-starting names for classes) is a sort-of pure Object-Oriented Programming convention ("pure" is meant as in: without any other programming paradigms like generic programming or template meta-programming). It is mostly used in Java (or by Java "natives" who are programming C++). I personally don't like it and know few people who do. I'm always a bit annoyed when working within a framework or project that adopts this notation, it de-tones with the standard libraries, boost libraries, and the overall proper usage of namespaces.
My recommendation is to always look at a language's standard libraries for examples of set a coding convention. The result is that your code will read more naturally for the language in which it is written. Basically, write C++ that looks like it could be part of the ISO C++ documents.
For C++, the standard containers, iterators and algorithms have many templates you can use as examples.
As a counter example, using camel case will make your C++ code to read like Java. When you end up using things from the standard library along side your own code, it will look weird.
That said, there are two exceptions to consider. Firstly, if you already have a large code base, follow what's already there: a mix of styles is confusing. Secondly, there are excellent libraries, such as Qt, that do not follow the style of the standard libraries, they are also worthy as examples of coding standards.
* Member variables prefixed with 'm' or 'm_'
Questionable.
* Class prefix (generally project specific, ie in Qt all class names are prefixed with 'Q')
Terrible. Was a necessary practice back in the day.
Big three isn't really a standard either and has pretty much been superceeded as a good practice by the Big Two (because using RAII for pointers negates the necessity of a destructor even when you need Copy ctr and assignment).
At any rate....
You need to differentiate your template parameters from normal code. Thus, you should use a naming convention that you are not using in standard code for template parameters. One good method, used by a good many, is to use CamelCase for template parameters. Another important aspect is, since C++ doesn't enforce concepts at all, to name your parameters after the concept they expect. ForwardIter thus makes a good parameter name for a parameter than should be a forward iterator.
Of course, if you're already using CamelCase for your class names (Java programmers - blech :p) then you should use something else.
When you get into complex instantiations and such then you need to use some method of declaring your template instantiations in multiple lines. When metaprogramming you also often need to split things up into multiple lines and/or multiple types/templates. It's one of those learn as you go things. I like the following method:
template < typename MyParams >
struct my_metafunction
: mpl::if_
<
check // probably wouldn't actually split this one since it's trivial...but as example...
<
MyParams
>
, some_type_expression
, some_other_type_expression
>
{};
There are no "common conventions" for names. Even the conventions you mention aren't as common as you might think. I can't think of anyone using m or m_ prefix for class member data other than a subset of Windows developers. Similarly for prefixing class names.
Conventions of this sort are very project-specific. You agree about them in a project and move on. When you start a new project it's perfectly alright to have new conventions if you so desire. If you lack imagination or confidence to pick your own conventions then buy Herb Sutter and Andrei Alexandrescu's C++ Coding Standards book. In fact, you should really read it because it deals with far more effective conventions than naming conventions. With things that actually matter.
If it at all helps I sometimes see people choosing for template parameters short names that start with a capital letter. E.g., template<class Ch, class Tr>. Look in your compiler's standard library for inspiration.
Take a look at Boost if you want to see their coding convention.
Like the others say, it depends on the project coding style. I like using lowercase letters separated with under score while coding. And for the harmony I use lowercase letters for template parameters too. To distinguish them from the others, I start with underscore and end with "_t".
`
template<typename _encoder_t>
class compression
{
typedef typename _encoder_t::settings settings_t;
...
};
`

What's the principle of template in C++?

And which templating library should new beginner user?
Not sure if OS matter,I'm talking about windows if that matters.
Templates are all about generic programming. The concept is like: you define a function body/class that will work with any kind of data (having some properties, like a specific operator defined). Consider you are writing a function that will return summation of its given parameters:
int sum(int a, int b)
{
return a + b;
}
Now you want that the function should work for strings as well. But you can't do the following:
std::string s1 = "abc", s2 = "def";
std::string s = sum(s1, s2);
For this sum() calling you need to define another version of sum(). Templates will save your work. Just write the definition of sum() in following way:
template<typename T>
T sum(const T& a, const T& b)
{
return a + b;
}
Now the function sum() will work for any data type for which operator+ is defined.
EDIT
You need to learn STL (Standard Template Library) first, if you want to be a C++ programmer.
For beginner it is better to start from a good book. And the Standard Library (often also called STL) is the template library you should start from.
Templates are a feature of the core C++ language, and implemented by all C++ compilers. You can write a template without using any library. That just means that you have to provide all of the template code; the compiler will turn that code into the appropriate assembly as needed.
The core idea behing templates is the notion of generic code. The code you need to for a linked list of integers looks almsot the same as the code for a linked list of strings; for an array of integers almost the same as an array of strings. Templates allow you to write a linked list of T objects, wihout specifying T up front. Then, when you need a linked list of integers, you just tell the compiler to instantiate that linked list with T==int.
Now, linked lists are quite common. You therefore don't have to write the linked list template; the Standard Library (included with every compiler) contains the std::list<T> template. To use it, just tell the compiler what kind of list you need. std::list<float>, std::list<std::string>, etcetera. In addition to such container classes, there are also algorithms. Those too are templates - std::sort< > can sort many different containers. Unlike qsort from C, the C++ compiler knows what it is sorting, and that makes std::sort< > faster.
The ATL is a microsoft library. It uses templates for the same reason as the Standard Library - not as a goal in itself, but because it allowed Microsoft to write code that you can then tailor for your particular need. For instance, there are thousands of COM interfaces. The ATL doesn't need to provide different code for each and every COM interface; instead it provides a few templates that are instantaited for every COM interafce you want to use.
principle? I'd have to say it boils down mostly to not 're-inventing the wheel' and rapid application development(RAD), by creating generic code that can be reused in differect situations just by chnaging the template parameters. a good example of this is std::list or std::vector
As for what to use, well that depends on your goals(ie: what sort or pragram are you making, what will it need to do?), generally though you can use either boost and/or the STL libraries that ship with most compilers these days

Features of C++ that can't be implemented in C?

I have read that C++ is super-set of C and provide a real-time implementation by creating objects. Also C++ is closed to real world as it is enriched with Object Oriented concepts.
What all concepts are there in C++ that can not be implemented in C?
Some say that we can not over write methods in C then how can we have different flavors of printf()?
For example printf("sachin"); will print sachin and printf("%d, %s",count ,name); will print 1,sachin assuming count is an integer whose value is 1 and name is a character array initililsed with "sachin".
Some say data abstraction is achieved in C++, so what about structures?
Some responders here argues that most things that can be produced with C++ code can also be produced with C with enough ambition. This is true in some parts, but some things are inherently impossible to achieve unless you modify the C compiler to deviate from the standard.
Fakeable:
Inheritance (pointer to parent-struct in the child-struct)
Polymorphism (Faking vtable by using a group of function pointers)
Data encapsulation (opaque sub structures with an implementation not exposed in public interface)
Impossible:
Templates (which might as well be called preprocessor step 2)
Function/method overloading by arguments (some try to emulate this with ellipses, but never really comes close)
RAII (Constructors and destructors are automatically invoked in C++, so your stack resources are safely handled within their scope)
Complex cast operators (in C you can cast almost anything)
Exceptions
Worth checking out:
GLib (a C library) has a rather elaborate OO emulation
I posted a question once about what people miss the most when using C instead of C++.
Clarification on RAII:
This concept is usually misinterpreted when it comes to its most important aspect - implicit resource management, i.e. the concept of guaranteeing (usually on language level) that resources are handled properly. Some believes that achieving RAII can be done by leaving this responsibility to the programmer (e.g. explicit destructor calls at goto labels), which unfortunately doesn't come close to providing the safety principles of RAII as a design concept.
A quote from a wikipedia article which clarifies this aspect of RAII:
"Resources therefore need to be tied to the lifespan of suitable objects. They are acquired during initialization, when there is no chance of them being used before they are available, and released with the destruction of the same objects, which is guaranteed to take place even in case of errors."
How about RAII and templates.
It is less about what features can't be implemented, and more about what features are directly supported in the language, and therefore allow clear and succinct expression of the design.
Sure you can implement, simulate, fake, or emulate most C++ features in C, but the resulting code will likely be less readable, or maintainable. Language support for OOP features allows code based on an Object Oriented Design to be expressed far more easily than the same design in a non-OOP language. If C were your language of choice, then often OOD may not be the best design methodology to use - or at least extensive use of advanced OOD idioms may not be advisable.
Of course if you have no design, then you are likely to end up with a mess in any language! ;)
Well, if you aren't going to implement a C++ compiler using C, there are thousands of things you can do with C++, but not with C. To name just a few:
C++ has classes. Classes have constructors and destructors which call code automatically when the object is initialized or descrtucted (going out of scope or with delete keyword).
Classes define an hierarchy. You can extend a class. (Inheritance)
C++ supports polymorphism. This means that you can define virtual methods. The compiler will choose which method to call based on the type of the object.
C++ supports Run Time Information.
You can use exceptions with C++.
Although you can emulate most of the above in C, you need to rely on conventions and do the work manually, whereas the C++ compiler does the job for you.
There is only one printf() in the C standard library. Other varieties are implemented by changing the name, for instance sprintf(), fprintf() and so on.
Structures can't hide implementation, there is no private data in C. Of course you can hide data by not showing what e.g. pointers point to, as is done for FILE * by the standard library. So there is data abstraction, but not as a direct feature of the struct construct.
Also, you can't overload operators in C, so a + b always means that some kind of addition is taking place. In C++, depending on the type of the objects involved, anything could happen.
Note that this implies (subtly) that + in C actually is overridden; int + int is not the same code as float + int for instance. But you can't do that kind of override yourself, it's something for the compiler only.
You can implement C++ fully in C... The original C++ compiler from AT+T was infact a preprocessor called CFront which just translated C++ code into C and compiled that.
This approach is still used today by comeau computing who produce one of the most C++ standards compliant compilers there is, eg. It supports all of C++ features.
namespace
All the rest is "easily" faked :)
printf is using a variable length arguments list, not an overloaded version of the function
C structures do not have constructors and are unable to inherit from other structures they are simply a convenient way to address grouped variables
C is not an OO langaueage and has none of the features of an OO language
having said that your are able to imitate C++ functionality with C code but, with C++ the compiler will do all the work for you in compile time
What all concepts are there in C++
that can not be implemented in C?
This is somewhat of an odd question, because really any concept that can be expressed in C++ can be expressed in C. Even functionality similar to C++ templates can be implemented in C using various horrifying macro tricks and other crimes against humanity.
The real difference comes down to 2 things: what the compiler will agree to enforce, and what syntactic conveniences the language offers.
Regarding compiler enforcement, in C++ the compiler will not allow you to directly access private data members from outside of a class or friends of the class. In C, the compiler won't enforce this; you'll have to rely on API documentation to separate "private" data from "publicly accessible" data.
And regarding syntactic convenience, C++ offers all sorts of conveniences not found in C, such as operator overloading, references, automated object initialization and destruction (in the form of constructors/destructors), exceptions and automated stack-unwinding, built-in support for polymorphism, etc.
So basically, any concept expressed in C++ can be expressed in C; it's simply a matter of how far the compiler will go to help you express a certain concept and how much syntactic convenience the compiler offers. Since C++ is a newer language, it comes with a lot more bells and whistles than you would find in C, thus making the expression of certain concepts easier.
One feature that isn't really OOP-related is default arguments, which can be a real keystroke-saver when used correctly.
Function overloading
I suppose there are so many things namespaces, templates that could not be implemented in C.
There shouldn't be too much such things, because early C++ compilers did produce C source code from C++ source code. Basically you can do everything in Assembler - but don't WANT to do this.
Quoting Joel, I'd say a powerful "feature" of C++ is operator overloading. That for me means having a language that will drive you insane unless you maintain your own code. For example,
i = j * 5;
… in C you know, at least, that j is
being multiplied by five and the
results stored in i.
But if you see that same snippet of
code in C++, you don’t know anything.
Nothing. The only way to know what’s
really happening in C++ is to find out
what types i and j are, something
which might be declared somewhere
altogether else. That’s because j
might be of a type that has operator*
overloaded and it does something
terribly witty when you try to
multiply it. And i might be of a type
that has operator= overloaded, and the
types might not be compatible so an
automatic type coercion function might
end up being called. And the only way
to find out is not only to check the
type of the variables, but to find the
code that implements that type, and
God help you if there’s inheritance
somewhere, because now you have to
traipse all the way up the class
hierarchy all by yourself trying to
find where that code really is, and if
there’s polymorphism somewhere, you’re
really in trouble because it’s not
enough to know what type i and j are
declared, you have to know what type
they are right now, which might
involve inspecting an arbitrary amount
of code and you can never really be
sure if you’ve looked everywhere
thanks to the halting problem (phew!).
When you see i=j*5 in C++ you are
really on your own, bubby, and that,
in my mind, reduces the ability to
detect possible problems just by
looking at code.
But again, this is a feature. (I know I will be modded down, but at the time of writing only a handful of posts talked about downsides of operator overloading)