Search code examples
c++templatesc++03template-argument-deduction

Confused by template argument deduction


I've created the following struct:

template<class T>
struct not_equals
{
  not_equals(T d):data(d){};
  bool operator()(T const & in)
  {
    return data != in;
  }
  T data;
};

My expectation was that since I need to pass some value of concrete type d to the constructor, template argument T will be deduced from type of d.

However, this does not happens.

not_equals('0'); // fails with 'missing template arguments'
char zero = '0';
not_equals(zero); // same as above
not_equals<char>('0'); // compiles without errors

What is the reason for compiler not recognizing type of template argument?


Solution

  • c++17 will allow class template deduction

    Until then, you can create a "make" function:

    template <class T> auto make_not_equals(const T& d) -> not_equals<T>
    {
      return {d};
    }
    
    auto z = make_not_equals('0');
    

    This is the C++03 version of the make function:

    template <class T> not_equals<T> make_not_equals(const T& d)
    {
        return not_equals<T>(d);
    }
    

    Unfortunately when you declare a variable you need to spell the whole type with the template because of missing auto feature, but the make function can still be helpful in a deduced context, for instance for a parameter:

    template <class T> void foo(not_equals<T> ne);
    
    void test()
    {
       foo(make_not_equals('0'));
    }