Search results
Top results related to generic programming in c++
Top Answer
Answered Oct 30, 2021 · 1 votes
clrscr() is an obsolete function that clears the console screen that was used in some old Borland Turbo C++ compilers. Your program should work also without it, so you can delete it.
There's another error, though:
else if (vari=vari2)-
This does not do comparison between those variables, instead it assigns vari2 to vari1. Fix it like this:
else if (vari==vari2)-
1/5
Top Answer
Answered Feb 19, 2013 · 63 votes
Generic programming means that you are not writing source code that is compiled as-is but that you write "templates" of source codes that the compiler in the process of compilation transforms into source codes. The simplest example for generic programming are container classes like arrays, lists or maps that contain a collection of other objects. But there's much more to generic programming. In the context of C++ (and called meta programming) it means to write programs that are evaluated at compile time.
A basic example of generic programming are templates of containers: In a statically typed language like C++ you would have to declare separate containers that hold integers, floats, and other types or deal with pointers to void and therefore losing all type information. Templates which are the C++ way of generic programming leverage this constraint by letting you define classes where one or more parameters are unspecified at the time you define the class. When you instance the template later you tell the compiler which type it should use to create the class out of the template. Example:
template<typename T>class MyContainer{ // Container that deals with an arbitrary type T};-void main() { // Make MyContainer take just ints. MyContainer<int> intContainer;}
Templates are generic because the compiler translates the template into actual code. Note that in the case you don't instantiate your template no code will be generated for it at all. On the other hand, if you declare a MyContainer<int>, a MyContainer<float>, and a MyContainer<String> the compiler will create three versions of your code each of them having a different type. There will be some optimizations involved but basically your template code will be instantianted to three new types.
Iterators are a design pattern that were popularized in the seminal book "Design Patterns" by Gamma et al. It's a pattern to iterate over the content of a container class. Unlike using a for-loop an iterator is an instance of a class that points to a member of the container and gives you an unified interface to traverse the container as well as accessing the members. Take look at this example:
// Instanciate template QList with type intQList<int> myList;-// put some ints into myList-// Copyconstruct iterator that points to the// first member of the list.QList<int>::iterator i = myList.begin();// Iterate through the list while (i != myList.end()) { std::cout << *i << std::endl; i++;}
In this C++ example I'm instantating a template QList with type int. QList a container class that stores a list of objects. In this example we will use it to store integers.
Then I create an iterator i to traverse through the list. myList.begin() returns an iterator that points to the first element of the list. We can compare the iterator with another iterator myList.end() that points after the last element of the list. If both iterators are the same we know that we have passed the last elment. In the loop we're printing the element by accessing it with *i and go to the next element with i++.
Note that in this example * and ++ are overloaded operators and reimplemented by the iterator class. In a programming language without operator overloading there could be methods like i.element() or i.next() that do the same task. It's important to see that i is not a pointer but a whole class that just mimics the behaviour of a pointer.
What's the benefit of iterators? They provide a unified way to access the members of a container class, completely indepented on how the container class is implemented internally. No matter if your want to traverse a list, map or tree, the iterator classes (should) always work the same way.
Other Answers
Answered Oct 05, 2010 · 14 votes
Container
In C++, a container is a class that allows you to store objects. For example the standard library std::vector<T> is a resizable array which stores objects of some type T. In order to be formally considered a container class, it must expose certain functionality in order to facilitate generic programming. I could quote the exact requirements from the C++ standard, but for most purposes, the container classes that matter are the ones from the standard library: vector, deque, list, map, set and multimap/multiset.
One of the important requirements is that they must allow iterator access.
Iterator
"Iterator" can mean two things here: It is the name of a design pattern, but in C++ it is also the name of a specific expression of that design pattern. A C++ iterator is a type that allows traversal over a sequence of elements using a pointer-like syntax.
For example, if you have an array int a[10], you can use a plain pointer as an iterator:
int* first = a; // create an iterator that points to the beginning of the array++first; // make the iterator point to the second elementint i = *first; // get the value of the element pointed to by the iteratorint* last = a+10; //create an "end" iterator, one which points one past the end of the array-
If I had a linked list, such as std::list<int> l, I could do much the same, although now my iterators are no longer just pointers, but instead a class type implemented to work specifically with std::list:
std::list<int>::iterator first = l.begin(); // create an iterator that points to the beginning of the list++first; // make the iterator point to the second elementint i = *first; // get the value of the element pointed to by the iteratorstd::list<int>::iterator last = l.end(); //create an "end" iterator, one which points one past the end of the list-
or with a vector std::vector<int> v:
std::vector<int>::iterator first = v.begin(); // create an iterator that points to the beginning of the vector++first; // make the iterator point to the second elementint i = *first; // get the value of the element pointed to by the iteratorstd::list<int>::iterator last = v.end(); //create an "end" iterator, one which points one past the end of the vector-
The important thing about iterators is that they give us a uniform syntax for traversing sequences of elements, regardless of how the sequence is stored in memory (or even if it is stored in memory. An iterator could be written to iterate over the contents of a database on disk. Or we can use iterator wrappers to make a stream such as std::cin look like a sequence of objects too:
std::istream_iterator<int>(std::cin) first; ++first; // make the iterator point to the second element int i = *first; // get the value of the element pointed to by the iterator std::list<int>::iterator last; //create an "end" iterator, which marks the end of the stream-
although because this wraps a regular stream, it is a more limited type of iterator (you can't move backwards, for example, which means not all of the following algorithms work with stream iterators.
Now, given any of these iterator types, we can use all the standard library algorithms which are designed to work with iterators. For example, to find the first element in the sequence with value 4:
std::find(first, last, 4); // return the first iterator which equals 4 and which is located in the interval [first, last)-
Or we can sort the sequence (doesn't work with stream iterators):
std::sort(first, last);-
or if we write a function which squares an int, such as this:
int square(int i) { return i * i; }-
then we can apply it to the entire sequence:
// for every element in the range [first, last), apply the square function, and output the result into the sequence starting with firststd::transform(first, last, first, square);-
That's the advantage of iterators: they abstract away the details of the container, so that we can apply generic operations on any sequence. Thanks to iterators, the same find or sort implementation works with linked lists as well as arrays, or even with your own home-made container classes.
Generic Programming
Generic programming is basically the idea that your code should be as generic as possible. As shown in the iterator examples above, we come up with a common set of functionality that a type must support in order to be called an iterator, and then we write algorithms that work with any iterator type.
Compare this with traditional object-oriented programming, where iterators would have to "prove" that they're iterators by inheriting from some kind of IIterator interface. That would prevent us from using raw pointers as iterators, so we'd lose genericity.
In C++, with generic programming, we don't need the official interface. We just write the algorithms using templates, so they accept any type which just so happens to look like an iterator, regardless of where, when and how they're defined, and whether or not they derive from a common base class or interface.
Other Answers
Answered Mar 16, 2014 · 9 votes
In the simplest definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters.
2/5
Top Answer
Answered Mar 13, 2009 · 9 votes
1) a Lightweight beginner IDE [Eg: JCreator for Java] (Simple and small download)
Eclipse with CDT (~40 MB download) or Visual Studio 2008 Express edition (2.6 MB download for installer and then tons of stuff that it'll pull from the net) -- it's free. Also, get the SP1. But, I still suggest that you take a look at Visual Studio.
2) a full-blown advanced IDE [Eg: Eclipse for Java] (Every feature and huge download)
Eclipse with CDT (~40 MB download) or Visual Studio 2008 Professional (if you are going to pay).
3) should I use GCC or other compilers?
Yes and no. Depends on your needs. GNU g++ is great to get started with. However, hooking up with CDT may prove to be difficult.
If you intend to do professional Windows programming in near future, it is best to buy the Visual Studio 2008 Pro (and install SP1) and get used to it.
Other Answers
Answered Oct 05, 2010 · 14 votes
Container
In C++, a container is a class that allows you to store objects. For example the standard library std::vector<T> is a resizable array which stores objects of some type T. In order to be formally considered a container class, it must expose certain functionality in order to facilitate generic programming. I could quote the exact requirements from the C++ standard, but for most purposes, the container classes that matter are the ones from the standard library: vector, deque, list, map, set and multimap/multiset.
One of the important requirements is that they must allow iterator access.
Iterator
"Iterator" can mean two things here: It is the name of a design pattern, but in C++ it is also the name of a specific expression of that design pattern. A C++ iterator is a type that allows traversal over a sequence of elements using a pointer-like syntax.
For example, if you have an array int a[10], you can use a plain pointer as an iterator:
int* first = a; // create an iterator that points to the beginning of the array++first; // make the iterator point to the second elementint i = *first; // get the value of the element pointed to by the iteratorint* last = a+10; //create an "end" iterator, one which points one past the end of the array
If I had a linked list, such as std::list<int> l, I could do much the same, although now my iterators are no longer just pointers, but instead a class type implemented to work specifically with std::list:
std::list<int>::iterator first = l.begin(); // create an iterator that points to the beginning of the list++first; // make the iterator point to the second elementint i = *first; // get the value of the element pointed to by the iteratorstd::list<int>::iterator last = l.end(); //create an "end" iterator, one which points one past the end of the list
or with a vector std::vector<int> v:
std::vector<int>::iterator first = v.begin(); // create an iterator that points to the beginning of the vector++first; // make the iterator point to the second elementint i = *first; // get the value of the element pointed to by the iteratorstd::list<int>::iterator last = v.end(); //create an "end" iterator, one which points one past the end of the vector
The important thing about iterators is that they give us a uniform syntax for traversing sequences of elements, regardless of how the sequence is stored in memory (or even if it is stored in memory. An iterator could be written to iterate over the contents of a database on disk. Or we can use iterator wrappers to make a stream such as std::cin look like a sequence of objects too:
std::istream_iterator<int>(std::cin) first; ++first; // make the iterator point to the second element int i = *first; // get the value of the element pointed to by the iterator std::list<int>::iterator last; //create an "end" iterator, which marks the end of the stream
although because this wraps a regular stream, it is a more limited type of iterator (you can't move backwards, for example, which means not all of the following algorithms work with stream iterators.
Now, given any of these iterator types, we can use all the standard library algorithms which are designed to work with iterators. For example, to find the first element in the sequence with value 4:
std::find(first, last, 4); // return the first iterator which equals 4 and which is located in the interval [first, last)
Or we can sort the sequence (doesn't work with stream iterators):
std::sort(first, last);
or if we write a function which squares an int, such as this:
int square(int i) { return i * i; }
then we can apply it to the entire sequence:
// for every element in the range [first, last), apply the square function, and output the result into the sequence starting with firststd::transform(first, last, first, square);
That's the advantage of iterators: they abstract away the details of the container, so that we can apply generic operations on any sequence. Thanks to iterators, the same find or sort implementation works with linked lists as well as arrays, or even with your own home-made container classes.
Generic Programming
Generic programming is basically the idea that your code should be as generic as possible. As shown in the iterator examples above, we come up with a common set of functionality that a type must support in order to be called an iterator, and then we write algorithms that work with any iterator type.
Compare this with traditional object-oriented programming, where iterators would have to "prove" that they're iterators by inheriting from some kind of IIterator interface. That would prevent us from using raw pointers as iterators, so we'd lose genericity.
In C++, with generic programming, we don't need the official interface. We just write the algorithms using templates, so they accept any type which just so happens to look like an iterator, regardless of where, when and how they're defined, and whether or not they derive from a common base class or interface.
Other Answers
Answered Mar 16, 2014 · 9 votes
In the simplest definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters.
3/5
Top Answer
Answered Dec 05, 2021 · 2 votes
Check the design rationale of boost geometry for a solution to this problem. The methodology boils down to these steps:
template <class Geometry>struct Position;-
template <>struct Position<MyAwesome2dPoint>{ static float getX(MyAwesome2dPoint const& p) { return p.x; } static float getY(MyAwesome2dPoint const& p) { return p.y; } }
class KdTree { template <class PointType> auto contains(PointType const& g) { // Geometric properties are accessed through the traits system. return contains_impl( Position<PointType>::getX(g), Position<PointType>::getY(g)); }}
template <class G>concept Positionable = requires (G g) { Position<G>::getX() + Position<G>::getY(); }; // So now you can explicitly operate on such typestemplate <Positionable G>auto contains(G const& g){}
- Declare a class template that extracts position information from a type, e.g. template <class Geometry>struct Position;
- To make your kd Tree usable with a new type, say MyAwesome2dPoint , specialize this template for it. In the specialization you can use the type's method of getting the position: template <>struct Position<MyAwesome2dPoint>{ static float getX(MyAwesome2dPoint const& p) { return p.x; } static float getY(MyAwesome2dPoint const& p) { return p.y; } }
- Use this type system in your kd tree, i.e. instead of directly accessing positions, go through the Position class: class KdTree { template <class PointType> auto contains(PointType const& g) { // Geometric properties are accessed through the traits system. return contains_impl( Position<PointType>::getX(g), Position<PointType>::getY(g)); }}
- For extra credit, create a concept to avoid the weird compilation errors when using a type that hasn't been configured to work with your library: template <class G>concept Positionable = requires (G g) { Position<G>::getX() + Position<G>::getY(); }; // So now you can explicitly operate on such typestemplate <Positionable G>auto contains(G const& g){}
No inheritance, no virtuals, no modifications to existing types. Just create a layer that can be specialized for everyone (even C types) and you're good to go. Concepts will save your life when abstracting even further, e.g. boost geometry generalizes to N dimensions, different coordinate systems and more.
4/5
Top Answer
Answered May 23, 2017 · 10 votes
It is not creating a second class, it is creating one class of type Stack where StackType is being supplanted by a user-given type. A better way to define this is to use typename (§14.1.2), which makes it more clear what is actually going on. For more information on templates, see C++ Templates.
What you are describing is nested classes in templates:
template <typename Type>class Stack{public: class InnerType { };};
In this example, InnerType is a class whose strong name is Stack<Type>::InnerType, which is a specific class based on the provided type. So if somewhere in code an object is created as follows:
auto x = new Stack<int>();
then a class of type Stack<int>::InnerType will exist. Template classes only exist in the assembly when they are used in code, so if no objects of any variation of Stack are implemented, the InnerType (of any template type) will not exist.
Also further detail about declaring templates is discussed here on SO.
5/5
www.geeksforgeeks.org › generics-in-cGenerics in C++ - GeeksforGeeks
www.geeksforgeeks.org › generics-in-cApr 1, 2019 · Learn how to use templates to implement generic programming in C++, which allows writing a general algorithm that works with any data type. See examples of generic functions, classes and multi-type generics.
stackoverflow.com › questions › 3862378What is the meaning of "generic programming" in c++?
stackoverflow.com › questions › 3862378Learn what generic programming means in C++, how templates and iterators are used to implement it, and what container classes are. See examples, definitions, and answers from experts and beginners.
Code sample
QList<int> myList;QList<int>::iterator i = myList.begin();while (i != myList.end()) {std::cout << *i << std::endl;i++;...www.scaler.com › topics › cppGeneric Programming in C++ - Scaler Topics
www.scaler.com › topics › cppJun 29, 2022 · Learn how to use templates in C++ to write data type independent code with generics. See examples of function templates, class templates, inheritance, and static variables with templates.
People also ask
What is generic programming in C++?
- Generic programming is of course more than just templates of containers. In C++, a container is a class that allows you to store objects. For example the standard library std::vector is a resizable array which stores objects of some type T.
What is the meaning of "generic programming" in c++?
stackoverflow.com/questions/3862378/what-is-the-meaning-of-generic-programming-in-cWhat is generic programming pattern in C++?
- The generic programming pattern generalizes the algorithm with the help of templates in C++ so that it can be used along with different data types. In templates, we specify a placeholder instead of the actual data type, and that placeholder gets replaced with the data type used during the compilation.
Generic Programming in C++ - Scaler Topics
www.scaler.com/topics/cpp/generic-programming-in-cpp/What is generic programming?
- The method of Generic Programming is implemented to increase the efficiency of the code. Generic Programming enables the programmer to write a general algorithm which will work with all data types. It eliminates the need to create different algorithms if the data type is an integer, string or a character. The advantages of Generic Programming are
Generics in C++ - GeeksforGeeks
www.geeksforgeeks.org/generics-in-c/How to implement generics in C++?
- Generics can be implemented in C++ using Templates. Template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort () for different data types.
Generics in C++ - GeeksforGeeks
www.geeksforgeeks.org/generics-in-c/en.wikipedia.org › wiki › Generic_programmingGeneric programming - Wikipedia
en.wikipedia.org › wiki › Generic_programmingThe D programming language also offers fully generic-capable templates based on the C++ precedent but with a simplified syntax. The Java programming language has provided genericity facilities syntactically based on C++'s since the introduction of Java Platform, Standard Edition (J2SE) 5.0.
en.cppreference.com › w › cGeneric selection (since C11) - cppreference.com
en.cppreference.com › w › cJun 25, 2023 · The type-generic math macros from <tgmath.h>, introduced in C99, were implemented in compiler-specific manner. Generic selections, introduced in C11, gave the programmers the ability to write similar type-dependent code. Generic selection is similar to overloading in C++ (where one of several functions is chosen at compile time based on the ...
www.generic-programming.org › languages › cppGeneric Programming in C++
www.generic-programming.org › languages › cppMay 27, 2011 · Learn how C++ supports Generic Programming through templates, which provide parametric polymorphism and instantiation. Find out how to use C++ for Generic Programming, Generative Programming, and Template Metaprogramming.
www.generic-programming.org › about › introAn Introduction to Generic Programming
www.generic-programming.org › about › introMay 27, 2011 · Learn how to develop efficient, reusable software libraries using Generic Programming, a paradigm pioneered by Stepanov and Musser. Find out how to balance lifting and specialization processes to achieve maximal reusability and performance.
Searches related to generic programming in c++
object-oriented programming in c++