Member Functions with Generic Parameters

Someone wanted to write a C++ class member function to operate on a generic container.

His thought process was: “Since in C++14 we can use auto with lambda parameters, why not using it also for class method parameters?

class MyClass {
  ...

  // DOESN’T work in C++14!!
  void DoSomething(auto& container) {
    ...

Unfortunately, this code doesn’t compile. In fact, in C++14 “auto” is not a valid parameter type for member functions.

Visual Studio 2015 emits the following error:

error C3533: a parameter cannot have a type that contains ‘auto’

To fix that code, we can use templates. The member function with an “auto” parameter can be written as a member function template:

class MyClass {
  ...

  //
  // Simulate:
  //
  //   void DoSomething(auto& container)
  //
  // using templates.
  //
  template <typename Container>
  void DoSomething(Container& container) {
    ...

Leave a Reply

Your email address will not be published. Required fields are marked *