There is a wrapper for a tuple, it describes the function of access to the elements of the tuple. This wrapper is used in the template function of a class that performs the search for a specified type. Here is the code template function:  template &lt;   Calculating::CalculateTypes calculateType,   class SourceDataType = typename calculating_list_type::template strategy_type_selector&lt;calculateType&gt;::source_data_type &gt; auto calculate(const SourceDataType &amp; sourceData)   -&gt; decltype(typename calculating_list_type::template strategy_type_selector&lt;calculateType&gt;::result_type()) {   auto&amp; strategy = _calculates.lookup&lt;calculateType&gt;(); //error in this place...    strategy.setSourceData(sourceData);   strategy.calculate();    return strategy.getResult(); }   In this context, _calculates is a member of the class, which we call the function, the type of data: calculating_list_type  Here's the code to access the wrapper function tuple:  template&lt;CalculateTypes calculateType&gt; inline auto lookup()   -&gt; decltype(std::get&lt;Private::IndexOfList&lt;calculateType, StrategyTypes...&gt;::value&gt;(_calculatingTuple)) {    return std::get&lt;Private::IndexOfList&lt;calculateType, StrategyTypes...&gt;::value&gt;(_calculatingTuple); }   What is most interesting is that a template function access function works perfectly for example:  std::cout &lt;&lt; es.getCalculateList().lookup&lt;Calculating::CalculateTypes::MAIN_VOLUME&gt;().getName() &lt;&lt; std::endl;// works great...   What did I do wrong?
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?
53471
Now that it's clear , there is an associated concept that I use all the time without knowing what it really means.   I suppose everybody made once a mistake with parenthesis, resulting  in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for.  Could you give me some explanations, including examples with the magic method ?
104904
I really should be able to get this, but I'm just to the point where I think it'd be easier to ask.  In the C# function:  public static T GetValue&lt;T&gt;(String value) where T:new() {    //Magic happens here }   What's a good implementation for the magic? The idea behind this is that I have xml to parse and the desired values are often primitives (bool, int, string, etc.) and this is the perfect place to use generics... but a simple solution is eluding me at the moment.  btw, here's a sample of the xml I'd need to parse  &lt;Items&gt;     &lt;item&gt;         &lt;ItemType&gt;PIANO&lt;/ItemType&gt;         &lt;Name&gt;A Yamaha piano&lt;/Name&gt;         &lt;properties&gt;             &lt;allowUpdates&gt;false&lt;/allowUpdates&gt;             &lt;allowCopy&gt;true&lt;/allowCopy&gt;         &lt;/properties&gt;        &lt;/item&gt;     &lt;item&gt;         &lt;ItemType&gt;PIANO_BENCH&lt;/ItemType&gt;         &lt;Name&gt;A black piano bench&lt;/Name&gt;         &lt;properties&gt;             &lt;allowUpdates&gt;true&lt;/allowUpdates&gt;             &lt;allowCopy&gt;false&lt;/allowCopy&gt;             &lt;url&gt;www.yamaha.com&lt;/url&gt;         &lt;/properties&gt;     &lt;/item&gt;     &lt;item&gt;         &lt;ItemType&gt;DESK_LAMP&lt;/ItemType&gt;         &lt;Name&gt;A Verilux desk lamp&lt;/Name&gt;         &lt;properties&gt;             &lt;allowUpdates&gt;true&lt;/allowUpdates&gt;             &lt;allowCopy&gt;true&lt;/allowCopy&gt;             &lt;quantity&gt;2&lt;/quantity&gt;         &lt;/properties&gt;     &lt;/item&gt; &lt;/Items&gt;
108226
I'm trying to write a function that formats every (string) member/variable in an object, for example with a callback function. The variable names are unknown to me, so it must work with objects of all classes.  How can I achieve something similar to array_map or array_walk with objects?
29017
I'm asking for a template trick to detect if a class has a specific member function of a given signature.  The problem is similar to the one cited here  but not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE  a member function with a particular signature, else the program won't compile. In my problem I need to do something if a class has that function, else do "something else".   A similar problem was faced by boost::serialization but I don't like the solution they adopted: a template function that invokes by default a free function (that you have to define) with a particular signature unless you define a particular member function (in their case "serialize" that takes 2 parameters of a given type) with a particular signature, else a compile error will happens. That is to implement both intrusive and non-intrusive serialization.   I don't like that solution for two reasons:   To be non intrusive you must override the global "serialize" function that is in boost::serialization namespace, so you have IN YOUR CLIENT CODE to open namespace boost and namespace serialization! The stack to resolve that mess was 10 to 12 function invocations.   I need to define a custom behavior for classes that has not that member function, and my entities are inside different namespaces (and I don't want to override a global function defined in one namespace while I'm in another one)  Can you give me a hint to solve this puzzle?
1377
Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++?  MyObject  object;  // ok - default ctor MyObject  object(blah); // ok  MyObject  object();  // error   I seem to type "()" automatically everytime. Is there a good reason this isn't allowed?
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.)
86715
I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is  if you want to look at all of the code.  Here are the important parts:  private RpcMap map;  public &lt;X&gt; X get(String property) {   if (allowNestedValues &amp;&amp; NestedModelUtil.isNestedProperty(property)) {     return (X)NestedModelUtil.getNestedValue(this, property);   }   return map == null ? null : (X) map.get(property); }   X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the &lt;X&gt; in the public method signature.  I've tried to call this method with the following two examples to see what happens:  public Date getExpiredate() {     return  get("expiredate"); }  public String getSubject() {     return  get("subject"); }   They compile and show no errors or warnings.  I would think at the very least I would have to do a cast to get this to work.  Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime?  This seems counter to what generics are supposed to do.  Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better?  I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.
22118
When writing xml documentation you can use &lt;see cref="something"&gt;something&lt;/see&gt;, which works of course. But how do you reference a class or a method with generic types?   public class FancyClass&lt;T&gt; {   public string FancyMethod&lt;K&gt;(T value) { return "something fancy"; } }   If I was going to write xml documentation somewhere, how would I reference the fancy class? how can I reference a FancyClass&lt;string&gt;? What about the method?  For example in a different class I wanted to let the user know that I will return an instance of FancyClass&lt;int&gt;. How could I make a see cref thing for that?
36534
Having recently introduced an overload of a method the application started to fail. Finally tracking it down, the new method is being called where I did not expect it to be.  We had  setValue( const std::wstring&amp; name, const std::wstring&amp; value );  std::wstring avalue( func() ); setValue( L"string", avalue ); std::wstring bvalue( func2() ? L"true", L"false" ); setValue( L"bool", bvalue ); setValue( L"empty", L"" );   It was changed so that when a bool value is stored we use the same strings (internal data storage of strings)  setValue( const std::wstring&amp; name, const std::wstring&amp; value ); setValue( const std::wstring&amp; name, const bool&amp; value );  std::wstring avalue( func() ); setValue( L"string", avalue ); setValue( L"bool", func2() ); setValue( L"empty", L"" ); &lt;&lt; --- this FAILS!?!   The problem with L"" is that it is implicitly casting and previously it was happy to be a std::wstring, but not it prefers to be a bool. The MSVC compiler does not complain, or raise warning, so I'm worried that even if I "fix" the setValue( L"empty", L"" ); to be  setValue( L"empty", std::wstring() );   somebody else may come later and simply use setValue( L"empty", L"" ); and have to track down this issue again.  We thought to use explicit on the method but it is not a valid keyword for this usage. Is there some way to get the compiler to complain about this, or otherwise prevent the issue?  Otherwise I'm thinking to change the name of the method which takes a bool to ensure it can't make an incorrect guess.
65868
There's a good discussion of Generics and what they really do behind the scenes over at , so we all know that Vector&lt;int[]&gt; is a vector of integer arrays, and HashTable&lt;String, Person&gt; is a table of whose keys are strings and values Persons.  However, what stumps me is the usage of Class&lt;&gt;.  The java class Class is supposed to also take a template name, (or so I'm being told by the yellow underline in eclipse).  I don't understand what I should put in there.  The whole point of the Class object is when you don't fully have the information about an object, for reflection and such.  Why does it make me specify which class the Class object will hold?  I clearly don't know, or I wouldn't be using the Class object, I would use the specific one.
7923
template&lt;typename T, size_t n&gt; size_t array_size(const T (&amp;)[n]) {     return n; }   The part that I don't get is the parameters for this template function. What happens with the array when I pass it through there that gives n as the number of elements in the array?
24567
I am trying to determine what issues could be caused by using the following serialization surrogate to enable serialization of anonymous functions/delegate/lambdas.   // see http://msdn.microsoft.com/msdnmag/issues/02/09/net/#S3 class NonSerializableSurrogate : ISerializationSurrogate {     public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)     {         foreach (FieldInfo f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))             info.AddValue(f.Name, f.GetValue(obj));     }      public object SetObjectData(object obj, SerializationInfo info, StreamingContext context,                                 ISurrogateSelector selector)     {         foreach (FieldInfo f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))             f.SetValue(obj, info.GetValue(f.Name, f.FieldType));         return obj;     } }     Listing 1 adapted from   The main issue I can think of that might be a problem is that the anonymous class is an internal compiler detail and it's structure is not guaranteed to remain constant between revisions to the .NET Framework. I'm fairly certain this is the case based on my research into the similar problem with iterators.  Background  I am investigating the serialization of anonymous functions. I was expecting this not to work, but found it did for some cases. As long as the lambda did *not&amp; force the compiler to generate an anonymous class everything works fine.   A SerializationException is thrown if the compiler requires a generated class to implement the anonymous function. This is because the compiler generated class is not marked as serializable.  Example  namespace Example {     [Serializable]     class Other     {         public int Value;     }      [Serializable]     class Program     {         static void Main(string[] args)         {             MemoryStream m = new MemoryStream();             BinaryFormatter f = new BinaryFormatter();              // Example 1             Func&lt;int&gt; succeeds = () =&gt; 5;             f.Serialize(m, succeeds);              // Example 2             Other o = new Other();             Func&lt;int&gt; fails = () =&gt; o.Value;             f.Serialize(m, fails); // throws SerializationException - Type 'Example.Program+&lt;&gt;c__DisplayClass3' in Assembly 'Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.         }     }   Listing 2  This is similar to the issue of trying to serialize iterators and I had found the following code in a previous search (see ) Using the code from Listing 1 and an ISurrogateSelector I was able to successfully serialize and deserialize the second failing example.  Objective  I have a system that is exposed via a web service. The system has a complex but small state (many objects, not a lot of properties per object). The state is saved in the ASP.NET Cache, but is also serialized to a BLOB in SQL in case of cache expiration. Some objects need to execute arbitrary "events" upon reaching some condition. Hence they have properties accepting Action/Func objects. Contrived example:      class Command     {         public Command(Action action, Func&lt;bool&gt; condition);     }   Somewhere else      void DoSomethingWithThing(Thing thing)     {         state = Store.GetCurrentState();          Command cmd = new Command(() =&gt; thing.Foo(), () =&gt; thing.IsReady())         state.Add(cmd);          Store.Save(state);     }
44272
EDIT:  I found out that I can get it to compile if I cast the IMetadataType object to the TMetadata type.  Why do I need to do this?  EDIT #2:  The "Values" property is a .NET dictionary of type &lt;TMetadata, TData&gt;.  I have this generic method:  private void FillMetadata&lt;TMetadata, TData&gt;     (Metadata&lt;TMetadata, TData&gt; oMetadata) where TMetadata : IMetadataType {     IMetadataType o;     oMetadata.Values.Add(o, (TData)(object)GetValue()); }   I have stripped the implementation to simplify it (I actually use a real object, not the IMetadataType declared here).  My question is, why doesn't this compile?  The compile error is on the Add() method:  "cannot convert from 'IMetadataType' to 'TMetadata'."  Isn't that what the "where" clause on the method is for?  What am I missing?
60879
Can anyone recommend any good resources for learning C++ Templates?  Many thanks.
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).
15076
I have code like this:  class RetInterface {...}  class Ret1: public RetInterface {...}  class AInterface {   public:      virtual boost::shared_ptr&lt;RetInterface&gt; get_r() const = 0;      ... };  class A1: public AInterface {   public:      boost::shared_ptr&lt;Ret1&gt; get_r() const {...}      ... };   This code does not compile.  In visual studio it raises     C2555: overriding virtual function return type differs and is not   covariant   If I do not use boost::shared_ptr but return raw pointers, the code compiles (I understand this is due to  in C++). I can see the problem is because boost::shared_ptr of Ret1 is not derived from boost::shared_ptr of RetInterface. But I want to return boost::shared_ptr of Ret1 for use in other classes, else I must cast the returned value after the return.      Am I doing something wrong?  If not, why is the language like this - it should be extensible to handle conversion between smart pointers in this scenario? Is there a desirable workaround?