The following is a Template classes tutorial from learncpp.com :  main.cpp  #include "Array.h"  int main() {     Array&lt;int&gt; intArray(12);     Array&lt;double&gt; doubleArray(12);      for (int count = 0; count &lt; intArray.getLength(); ++count)     {         intArray[count] = count;         doubleArray[count] = count + 0.5;     }      for (int count = intArray.getLength()-1; count &gt;= 0; --count)         std::cout &lt;&lt; intArray[count] &lt;&lt; "\t" &lt;&lt; doubleArray[count] &lt;&lt; '\n';      return 0; }  Array.h  #ifndef ARRAY_H #define ARRAY_H  #include &lt;assert.h&gt; // for assert()  template &lt;class T&gt; class Array { private:     int m_length;     T *m_data;  public:     Array()     {         m_length = 0;         m_data = nullptr;     }      Array(int length)     {         m_data = new T[length];         m_length = length;     }      ~Array()     {         delete[] m_data;     }      void Erase()     {         delete[] m_data;         // We need to make sure we set m_data to 0 here, otherwise it will         // be left pointing at deallocated memory!         m_data = nullptr;         m_length = 0;     }       T&amp; operator[](int index)     {         assert(index &gt;= 0 &amp;&amp; index &lt; m_length);         return m_data[index];     }      // The length of the array is always an integer     // It does not depend on the data type of the array     int getLength(); };  #endif   Array.cpp  #include "Array.h"  template &lt;typename T&gt; int Array&lt;T&gt;::getLength() { return m_length; }   Error : unresolved external symbol "public: int __thiscall Array::getLength(void)" (?GetLength@?$Array@H@@QAEHXZ)  Explanation : In order for the compiler to use a template, it must see both the template definition (not just a declaration) and the template type used to instantiate the template. Also remember that C++ compiles files individually. When the Array.h header is #included in main, the template class definition is copied into main.cpp. When the compiler sees that we need two template instances, Array, and Array, it will instantiate these, and compile them as part of main.cpp. However, when it gets around to compiling Array.cpp separately, it will have forgotten that we need an Array and Array, so that template function is never instantiated. Thus, we get a linker error, because the compiler can’t find a definition for Array::getLength() or Array::getLength().  What does the explanation mean? i am having a hard time understanding the explanation provided by Alex(learncpp's creator).
341
Quote from :     The only portable way of using templates at the moment is to implement them in header files by using inline functions.   Why is this?  (Clarification: header files are not the only portable solution. But they are the most convenient portable solution.)
51785
I'd like to implement a big int class in C++ as a programming exercise&mdash;a class that can handle numbers bigger than a long int.  I know that there are several open source implementations out there already, but I'd like to write my own.  I'm trying to get a feel for what the right approach is.  I understand that the general strategy is get the number as a string, and then break it up into smaller numbers (single digits for example), and place them in an array.  At this point it should be relatively simple to implement the various comparison operators.  My main concern is how I would implement things like addition and multiplication.  I'm looking for a general approach and advice as opposed to actual working code.
103430
My personal style with C++ has always to put class declarations in an include file, and definitions in a .cpp file, very much like stipulated in . Admittedly, part of the reason I like this style probably has to do with all the years I spent coding Modula-2 and Ada, both of which have a similar scheme with specification files and body files. I have a coworker, much more knowledgeable in C++ than I, who is insisting that all C++ declarations should, where possible, include the definitions right there in the header file. He's not saying this is a valid alternate style, or even a slightly better style, but rather this is the new universally-accepted style that everyone is now using for C++. I'm not as limber as I used to be, so I'm not really anxious to scrabble up onto this bandwagon of his until I see a few more people up there with him. So how common is this idiom really? Just to give some structure to the answers: Is it now The Way™, very common, somewhat common, uncommon, or bug-out crazy?
12579
I've allocated an "array" of mystruct of size n like this:  if (NULL == (p = calloc(sizeof(struct mystruct) * n,1))) {  /* handle error */ }   Later on, I only have access to p, and no longer have n. Is there a way to determine the length of the array given just the pointer p?  I figure it must be possible, since free(p) does just that. I know malloc() keeps track of how much memory it has allocated, and that's why it knows the length; perhaps there is a way to query for this information? Something like...  int length = askMallocLibraryHowMuchMemoryWasAlloced(p) / sizeof(mystruct)   I know I should just rework the code so that I know n, but I'd rather not if possible. Any ideas?
30298
In C++, what is the purpose of the scope resolution operator when used without a scope? For instance:  ::foo();
25980
suggested to have templates for tags. Their example was with the  tag on Stack Overflow.  I'm suggesting a more general approach:  Templates, Mark II  I suggest that each site will have a template. That template will prefill the  textbox when a new question is asked. However, it will be completely optional.  Something like (for Stack Overflow):  ## The Problem ## { Please tell us what the problem is with as many details as possible.   Include language, operating system, and any other relevant information.   Remember to add the relevant tags below, too. } ## Attempted Solutions ## { Please tell us what you've tried so far. Have you tried searching Google?    What queries? } ## Existing Code ## { Do you have any existing code to show? Please keep it short and simple.    We should be able to detect the problem right away. }   Why am I suggesting this?  Well, it seems as though most users will stick with the default. They don't bother to read, and so prefilling the question form for them with information that we know might be relevant, will forceWe'll get to that in a second them to actually stop and read.  Scenarios:   Best case: User arrives to ask a question, actually reads the template, fills the correct information in the placeholders. (Yeah, because that'll happen a lot) Neutral: User simply removes all of the template text and rewrites their own question. Result is exact same as we have currently. Worst case: User will ignore or misunderstand the template, will use it wrong or not at all and we'll get something like  &lt;template text here, still unfilled&gt; &lt;(crappy) question&gt;   This can be solved in a couple different ways. We could detect the template tags (i.e. { }, subject to discussion), and throw an error when a user attempts to post with them still available. We could also act more autonomously and remove placeholders which still exist.    Some more points:   Templates should be per-site, not per-tag. Sure, there are differences between the tags, but all questions are expected to have the same general information, and this isn't meant to be a rule, but a guideline to help write better questions. Site templates should be editable by that site's mods, like close reasons. We could autofocus on the first placeholder, and perhaps implement TAB to jump from one placeholder to the other, similar to mixins in IDEs. This doesn't have to be implemented everywhere. This suggestion makes sense to Stack Overflow or Superuser, but not to Anime &amp; Manga or Gaming All of the details are subject to discussion, and all discussion is welcomed.
80591
Although I'm doubtful, I'm curious as to whether it's possible to extract primitive-type template parameters from an existing type, perhaps using RTTI.  For example:  typedef std::bitset&lt;16&gt; WordSet;   Would it be possible to extract the number 16 in the above code without hard-coding it elsewhere? Compiler specific implementations are welcome, though I'm particularly interested in g++.
5014
I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages.   Basically I have three questions:   Why use pointers over normal variables? When and where should I use pointers? How do you use pointers with arrays?
44787
If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library.  I have always used Lists for 1d arrays.  What is the reason or circumstance where I would want to use the array module instead?  Is it for performance and memory optimization, or am I missing something obvious?
93897
If I have a template function, for example like this:  template&lt;typename T&gt; void func(const std::vector&lt;T&gt;&amp; v)   Is there any way I can determine within the function whether T is a pointer, or would I have to use another template function for this, ie:  template&lt;typename T&gt; void func(const std::vector&lt;T*&gt;&amp; v)   Thanks
99300
So, no matter what I seem to do, I cannot seem to avoid having Dev C++ spew out numerous Multiple Definition errors as a result of me including the same header file in multiple source code files in the same project.  I'd strongly prefer to avoid having to dump all my source code into one file and only include the header once, as that's going to make my file very long and difficult to manage.  Essentially, this is what's going on:  #ifndef _myheader_h #define _myheader_h  typedef struct MYSTRUCT{ int blah; int blah2; } MYSTRUCT;  MYSTRUCT Job_Grunt; MYSTRUCT *Grunt = &amp;Job_Grunt; MYSTRUCT Job_Uruk; MYSTRUCT *Uruk = &amp;Job_Grunt;  int Other_data[100];  void load_jobs();  #endif   Example Cpp File (They pretty much all look something like this):  #include "myheader.h"  void load_jobs(){  Grunt-&gt;blah = 1; Grunt-&gt;blah2 = 14;  Uruk-&gt;blah = 2; Uruk-&gt;blah2 = 15;  return; }   Bear in mind that I have about 5 cpp files that include this one header, each one dealing with a different type of struct found in the header file.  In this example there was only the one struct containing a couple of members, when there are about 4-6 different structs with many more members in the actual header file.  All the files I've included it in follow the same formula as you see in this example here.  Now I understand that the header guard only stops each individual cpp file from including the header file more than once.  What would seem to be happening is that when the compiler reads the include at the start of each cpp, it defines the header file all over again, which is causing it to spit out lines and lines of:  Multiple Definition of Uruk, first defined here   Multiple Definition of Job_Uruk, first defined here   Multiple Definition of Grunt, first defined here   Multiple Definition of Job_Grunt, first defined here   Multiple Definition of Other_data, first defined here   I'll see a set of this for just about every cpp file in the project which includes the header.  I've tried moving the definitions of the struct and the struct variables to the cpp files, but then the other cpp files cannot see them or work with them, which is very important as I need all files in the project to be able to work with these structs.  But the single most confusing part about this problem requires a little more explanation:  The way I'm setting up these multiple files in this project is identical to the book I'm working with, All In One Game Programming by John S. Harbour.  I ran into the exact same problems when I created the files for example projects in the book which called for one header included by multiple cpps in the same project.  I could type them out, word for word from the book, and I do mean word for word... and I'd get the series of MD errors for every cpp in the project.    If I loaded the example project from the CD included with the book, it would compile and run without a problem, allthough the files themselves, as well as the project options, were by all appearances identical to the ones I had created.  If I created my own project file, and simply added the source and header files for the example project from the CD, this, too, would also compile and run, though I can find no difference between those and mine.  So then, I tried making my own project file, then creating the blank source and header files and adding them to it, and then filling them by copying and pasting their contents from the files on the CD they were meant to correspond to(the same ones that had worked). And sure enough, I'd get the same thing...lines and lines of MD error messages.  I'm absolutely baffled.  I've repeated all these methods multiple times, and am certain I'm not mistyping or miscopying the code.  There just seems to be something about the premade files themselves; some configuration setting or something else I'm missing entirely...that will cause them to compile correctly while the files I make myself won't.
21871
I am trying to pass a reference to a two-dimensional array to a function in C++. I know the size of both dimensions at compile time. Here is what I have right now:  const int board_width = 80; const int board_height = 80; void do_something(int[board_width][board_height]&amp; array);  //function prototype   But this doesn't work. I get this error from g++:  error: expected ‘,’ or ‘...’ before ‘*’ token   What does this error mean, and how can I fix it?
983
I have some template code that I would prefer to have stored in a CPP file instead of inline in the header.  I know this can be done as long as you know which template types will be used.  For example:  .h file  class foo { public:     template &lt;typename T&gt;     void do(const T&amp; t); };   .cpp file  template &lt;typename T&gt; void foo::do(const T&amp; t) {     // Do something with t }  template void foo::do&lt;int&gt;(const int&amp;); template void foo::do&lt;std::string&gt;(const std::string&amp;);   Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link.  My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments.
7842
I notice that modern C and C++ code seems to use size_t instead of int/unsigned int pretty much everywhere - from parameters for C string functions to the STL.  I am curious as to the reason for this and the benefits it brings.
69483
I have code like this:  template &lt;typename T, typename U&gt; struct MyStruct {     T aType;     U anotherType; };  class IWantToBeFriendsWithMyStruct {     friend struct MyStruct; //what is the correct syntax here ? };   What is the correct syntax to give friendship to the template ?
8198
I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my computer from debian etch to lenny (g++ (Debian 4.3.2-1.1) 4.3.2 ) however I have the same problem on a Ubuntu system with the same g++.  Here is the relevant part of my matrix class:  namespace Math {     class Matrix     {     public:          [...]          friend std::ostream&amp; operator&lt;&lt; (std::ostream&amp; stream, const Matrix&amp; matrix);     } }   And the "implementation":  using namespace Math;  std::ostream&amp; Matrix::operator &lt;&lt;(std::ostream&amp; stream, const Matrix&amp; matrix) {      [...]  }   This is the error given by the compiler:     matrix.cpp:459: error: 'std::ostream&amp;   Math::Matrix::operator&lt;&lt;(std::ostream&amp;,   const Math::Matrix&amp;)' must take   exactly one argument   I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those 6 months. :-)
42167
The following code:  template &lt;typename S, typename T&gt; struct foo {    void bar(); };  template &lt;typename T&gt; void foo &lt;int, T&gt;::bar() { }   gives me the error  invalid use of incomplete type 'struct foo&lt;int, T&gt;' declaration of 'struct foo&lt;int, T&gt;'   (I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument:  template &lt;typename S&gt; struct foo {    void bar(); };  template &lt;&gt; void foo &lt;int&gt;::bar() { }   then it compiles correctly.