title: How to write a size() function that works on any type of collection objects?
body: <p>I require a simple way to obtain the count / length / size of an object of class <code>T</code> where <code>T</code> is some sort of collection type, such as a <code>std::map</code>, <code>std::list</code>, <code>std::vector</code>, <code>CStringArray</code>, <code>CString</code>, <code>std::string</code>, &hellip;</p>
  
  <p>For most of the standard types, <code>T::size()</code> is the correct answer, for most of the MFC classes <code>T::GetSize()</code> is correct and for <code>CString</code>, it is <code>T::GetLength()</code>.</p>
  
  <p>I want to have a like:</p>
  
  <pre><code>template &lt;typename T&gt; auto size(const T &amp; t)
  </code></pre>
  
  <p>...which evaluates to the correct member function call.</p>
  
  <p>It seems like there should be a simple way to invoke a traits template on <code>T</code> which has a <code>size(const T &amp; t)</code> member, which itself uses SFINAE to exist or not exist, and if it exists, then it is by definition calling an appropriate <code>t.size_function()</code> to return the count of elements in that instance of a <code>T</code>.</p>
  
  <p>I could write an elaborate <code>has_member</code> type-trait template - there are a few examples on stackoverflow - all of them quite convoluted for what seems to me "there must be a simpler approach". With C++ 17, it seems like this issue should be easily and elegantly solved?</p>
  
  <p>These discussions <a href="https://stackoverflow.com/questions/41936763/type-traits-to-check-if-class-has-member-function">here</a> and <a href="https://stackoverflow.com/questions/257288/is-it-possible-to-write-a-template-to-check-for-a-functions-existence">here</a> seems to use an inelegant solution with some of the answers using preprocessor macros to get the job done.  Is that still necessary?</p>
  
  <p>But... surely, there must be a way to use the fact that calling the correct member function on a <code>T</code> is compilable, and calling the wrong one fails to compile - can't that be used <strong>directly</strong> to create the correct type traits wrapper for a given type <code>T</code>?</p>
  
  <hr>
  
  <p>I would like something along the lines of:</p>
  
  <pre><code>template &lt;typename T&gt;
  auto size(const T &amp; collection)
  {
      return collection_traits&lt;T&gt;::count(collection);
  }
  </code></pre>
  
  <p>Where the exact specialization of <code>collection_traits&lt;T&gt;</code> is selected because it is the only one that fits for <code>T</code> (i.e. it calls the correct instance method).</p>