FYI I am using eclipse CDT on ubuntu. I am getting started with c++. I don't know what the issue is. One of my friends has shown me how to create a generic class with a different example. This is how he did it. I tried going through many other Stack Overflow questions but all of them had errors that my program didn't have. Thanks in advance.  Set.h:  #ifndef SET_H_ #define SET_H_  #include &lt;vector&gt;  template &lt;typename T&gt; class Set { private:     std::vector&lt;T&gt; _set_arr;  public:     Set();     ~Set();     void Add(T);     void Remove(int);      // FRIENDS     template &lt;typename S&gt;     friend Set&lt;S&gt;&amp; operator +(Set&lt;S&gt;, Set&lt;S&gt;); };   #endif /* SET_H_ */   Set.cpp:  #include "Set.h"  template &lt;typename T&gt; Set&lt;T&gt;::Set()     : _set_arr{} {}  template &lt;typename T&gt; Set&lt;T&gt;::~Set() {}  /**  * Adds a value to the Set  */ template &lt;typename T&gt; void Set&lt;T&gt;::Add(T val) {     _set_arr.push_back(val); }  /**  * Removes a value from the Set  */ template &lt;typename T&gt; void Set&lt;T&gt;::Remove(int index) {     _set_arr.erase(_set_arr.begin() + index); }  template &lt;typename S&gt; Set&lt;S&gt;&amp; operator +(Set&lt;S&gt; &amp;a, Set&lt;S&gt; &amp;b) {     Set&lt;S&gt; *_set_1 = new Set&lt;S&gt;;     // Pre-reserve     _set_1-&gt;_set_arr.reserve(         a._set_arr.size(), b._set_arr.size() );     // Insert     _set_1-&gt;_set_arr.insert(_set_1-&gt;_set_arr.end(), a._set_arr.begin(), a._set_arr.end() );     _set_1-&gt;_set_arr.insert(_set_1-&gt;_set_arr.end(), b._set_arr.begin(), b._set_arr.end() );     return *_set_1; }   Driver:  #include &lt;iostream&gt; #include "Set.h" using namespace std;  int main() {     Set&lt;int&gt; *s1 = new Set&lt;int&gt;;      return 0; }   Error Messages:  /home/ajay/code/eclipse_workspace/GenericSet/Debug/../src/main.cpp:14: undefined reference to `Set&lt;int&gt;::Set()' makefile:45: recipe for target 'GenericSet' failed /home/ajay/code/eclipse_workspace/GenericSet/Debug/../src/main.cpp:14: undefined reference to `Set&lt;int&gt;::~Set()'
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.)
55385
This is one of the possible ways I come out:  struct RetrieveKey {     template &lt;typename T&gt;     typename T::first_type operator()(T keyValuePair) const     {         return keyValuePair.first;     } };  map&lt;int, int&gt; m; vector&lt;int&gt; keys;  // Retrieve all keys transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());  // Dump all keys copy(keys.begin(), keys.end(), ostream_iterator&lt;int&gt;(cout, "\n"));   Of course, we can also retrieve all values from the map by defining another functor RetrieveValues.  Is there any other way to achieve this easily? (I'm always wondering why std::map does not include a member function for us to do so.)
18976
Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class?  Here's a simple example of what I would want to write:  template&lt;class T&gt; std::string optionalToString(T* obj) {     if (FUNCTION_EXISTS(T-&gt;toString))         return obj-&gt;toString();     else         return "toString not defined"; }   So, if class T has toString() defined, then it uses it; otherwise, it doesn't. The magical part that I don't know how to do is the "FUNCTION_EXISTS" part.
7208
Is it possible to forward declare an standard container in a header file?  For example, take the following code:  #include &lt;vector&gt;  class Foo { private:     std::vector&lt;int&gt; container_;     ... };   I want to be able to do something like this:  namespace std {     template &lt;typename T&gt; class vector; }  class Foo { private:     std::vector&lt;int&gt; container_;     ... };   Can this be done?
19841
I've been programming in C++ for a few years, and I've used STL quite a bit and have created my own template classes a few times to see how it's done.  Now I'm trying to integrate templates deeper into my OO design, and a nagging thought keeps coming back to me: They're just a macros, really... You could implement (rather UGLY) auto_ptrs using #defines, if you really wanted to.  This way of thinking about templates helps me understand how my code will actually work, but I feel that I must be missing the point somehow. Macros are meant evil incarnate, yet "template metaprogramming" is all the rage.  So, what ARE the real distinctions? and how can templates avoid the dangers that #define leads you into, like   Inscrutable compiler errors in places where you don't expect them? Code bloat?  Difficulty in tracing code? Setting Debugger Breakpoints?
22097
I'm currently working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a type_info class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. typeid(std::vector&lt;int&gt;).name() returns St6vectorIiSaIiEE.  Is there a way to produce something useful from this? Like std::vector&lt;int&gt; for the above example. If it only works for non-template classes, that's fine too.  The solution should work for gcc, but it would be better if I could port it. It's for logging so it's not so important that it can't be turned off, but it should be helpful for debugging.
33911
I have been reading through the  and was curious about the  declaration. I personally have never used it, however I am interested in exploring the language.   What is a good example of using friend?    Reading the FAQ a bit longer I like the idea of the &lt;&lt; &gt;&gt; operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?
122845
As most stories here begin, I was writing some code for a project that I was working on, and stumbled across an oddity when writing some unit tests. I was testing a method that has a Set&lt;sObject&gt; parameter, and I was attempting to pass this method a Set&lt;Account&gt;.  As Account inherits from sObject, I thought this would work fine. However, when running my test, I got the error     Method does not exist or incorrect signature: [TestClass].someMethod(Set&lt;Account&gt;)   Yes, the method that I was testing expects an argument of Set&lt;sObject&gt;, but an Account can be up-cast to an sObject, and Salesforce handles that implicitly, right?  Since Salesforce was throwing a fit when I tried to rely on implicit casting, the next thing I tried was explicitly up-casting. When I tried to explicitly up-cast my set, I was greeted with a different error     Line: someNumber, Column: otherNumber   Incompatible types since an instance of Set&lt;Account&gt; is never an instance of Set&lt;SObject&gt;   This can be reproduced with the following snippet  Set&lt;sObject&gt; testSet1; Set&lt;Account&gt; testSet2 = new Set&lt;Account&gt;();  testSet1 = (Set&lt;sObject&gt;)testSet2;   I haven't found anything in the documentation to suggest that up-casts for sets aren't allowed. Given that we can up-cast Lists and Maps, I feel this is rather unexpected.  Furthermore, knowing that an Apex set is really a Java HashSet in the back-end (look at the bottom of ), I tried to look for documentation to see if this is somehow dictated by Java, but I came up empty there as well.  I've been able to move on with my project, but this leaves me wondering...  Is there some documentation (Salesforce or Java) that explains this behavior? Failing that, can someone cobble together a feasible explanation for why Sets can't be up-cast?
701
Is there a reason why passing a reference to a std::map as const causes the [] operator to break? I get this compiler error (gcc 4.2) when I use const:     error: no match for ‘operator[]’ in   ‘map[name]’   Here's the function prototype:  void func(const char ch, std::string &amp;str, const std::map&lt;std::string, std::string&gt; &amp;map);   And, I should mention that there is no problem when I remove the const keyword in front of std::map.  If I've been instructed correctly, the [] operator will actually insert a new pair into the map if it doesn't find the key, which would of course explain why this happens, but I can't imagine that this would ever be acceptable behavior.  If there is a better method, like using find instead of [], I'd appreciate it. I can't seem to get find to work either though... I receive const mismatched iterator errors.
113560
I expected A::~A() to be called in this program, but it isn't:  #include &lt;iostream&gt;  struct A {   ~A() { std::cout &lt;&lt; "~A()" &lt;&lt; std::endl; } };  void f() {   A a;   throw "spam"; }  int main() { f(); }   However, if I change last line to   int main() try { f(); } catch (...) { throw; }   then A::~A() is called.  I am compiling with "Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86" from Visual Studio 2005. Command line is cl /EHa my.cpp.  Is compiler right as usual? What does standard say on this matter?
222
In several C++ examples I see a use of the type size_t where I would have used a simple int. What's the difference, and why size_t should be better?
211
In templates, where and why do I have to put typename and template on dependent names? What exactly are dependent names anyway?    I have the following code:  template &lt;typename T, typename Tail&gt; // Tail will be a UnionNode too. struct UnionNode : public Tail {     // ...     template&lt;typename U&gt; struct inUnion {         // Q: where to add typename/template here?         typedef Tail::inUnion&lt;U&gt; dummy;      };     template&lt; &gt; struct inUnion&lt;T&gt; {     }; }; template &lt;typename T&gt; // For the last node Tn. struct UnionNode&lt;T, void&gt; {     // ...     template&lt;typename U&gt; struct inUnion {         char fail[ -2 + (sizeof(U)%2) ]; // Cannot be instantiated for any U     };     template&lt; &gt; struct inUnion&lt;T&gt; {     }; };   The problem I have is in the typedef Tail::inUnion&lt;U&gt; dummy line. I'm fairly certain that inUnion is a dependent name, and VC++ is quite right in choking on it. I also know that I should be able to add template somewhere to tell the compiler that inUnion is a template-id. But where exactly? And should it then assume that inUnion is a class template, i.e. inUnion&lt;U&gt; names a type and not a function?
5777
I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this.
113468
I am working with an open-source UNIX tool that is implemented in C++, and I need to change some code to get it to do what I want. I would like to make the smallest possible change in hopes of getting my patch accepted upstream. Solutions that are implementable in standard C++ and do not create more external dependencies are preferred.  Here is my problem. I have a C++ class -- let's call it "A" -- that currently uses fprintf() to print its heavily formatted data structures to a file pointer. In its print function, it also recursively calls the identically defined print functions of several member classes ("B" is an example). There is another class C that has a member std::string "foo" that needs to be set to the print() results of an instance of A. Think of it as a to_str() member function for A.  In pseudocode:  class A { public:   ...    void print(FILE* f);   B b;    ...   };  ...  void A::print(FILE *f) {   std::string s = "stuff";   fprintf(f, "some %s", s);   b.print(f); }  class C {   ...   std::string foo;   bool set_foo(std::str);   ... }  ...  A a = new A(); C c = new C();  ...  // wish i knew how to write A's to_str() c.set_foo(a.to_str());   I should mention that C is fairly stable, but A and B (and the rest of A's dependents) are in a state of flux, so the less code changes necessary the better. The current print(FILE* F) interface also needs to be preserved. I have considered several approaches to implementing A::to_str(), each with advantages and disadvantages:   Change the calls to fprintf() to sprintf()   I wouldn't have to rewrite any format strings print() could be reimplemented as: fprint(f, this.to_str()); But I would need to manually allocate char[]s, merge a lot of c strings , and finally convert the character array to a std::string  Try to catch the results of a.print() in a string stream   I would have to convert all of the format strings to &lt;&lt; output format. There are hundreds of fprintf()s to convert :-{ print() would have to be rewritten because there is no standard way that I know of to create an output stream from a UNIX file handle (though ).  Use Boost's string    More external dependencies. Yuck. Format's syntax is different enough from printf() to be annoying:    printf(format_str, args) -> cout &lt;&lt; boost::format(format_str) % arg1 % arg2 % etc Use Qt's    A different external dependency.    So, have I exhausted all possible options? If so, which do you think is my best bet? If not, what have I overlooked?  Thanks.
67882
I am using the  and trying to create a table of 4 columns.   I get the error mentioned in the title of the question. I know the standard reasons why this error can occur.   But my question is: Is it possible that the template or .cls file is controlling the maximum number of columns in a table ? If it were, would I get a different error than this?
69582
Here's what I've been trying to do, in a nutshell:  class example &lt;T extends Number&gt; {     private int function(T number)     {         int x = (int) number;         ...     }     ... }   Basically, I'm trying to make it so that T is a number so I can convert it to an int inside that function. The problem is that I'm getting an "incovertible types" error, so I must be doing something wrong.
71365
I've been using C++ for a short while, and I've been wondering about the new keyword. Simply, should I be using it, or not?  1) With the new keyword...  MyClass* myClass = new MyClass(); myClass-&gt;MyField = "Hello world!";   2) Without the new keyword...  MyClass myClass; myClass.MyField = "Hello world!";   From an implementation perspective, they don't seem that different (but I'm sure they are)... However, my primary language is C#, and of course the 1st method is what I'm used to.  The difficulty seems to be that method 1 is harder to use with the std C++ classes.  Which method should I use?  Update 1:  I recently used the new keyword for heap memory (or free store) for a large array which was going out of scope (i.e. being returned from a function). Where before I was using the stack, which caused half of the elements to be corrupt outside of scope, switching to heap usage ensured that the elements were in tact. Yay!  Update 2:  A friend of mine recently told me there's a simple rule for using the new keyword; every time you type new, type delete.  Foobar *foobar = new Foobar(); delete foobar; // TODO: Move this to the right place.   This helps to prevent memory leaks, as you always have to put the delete somewhere (i.e. when you cut and paste it to either a destructor or otherwise).