Search code examples
c++templatestemplate-specializationfunction-signature

Specialized template for function signature


In that test code:

#include <string>
#include <iostream>

using namespace std;

template <typename T> class Signal;

template <typename T, typename U>
class Signal<T (U)>
{
public:
  Signal<T (U)>(T (*ptr)(U))
  {
  }
};

void Print(string const& str)
{
  cout << str << endl;
}

int main(int argc, char *argv[])
{
  Signal<void (string const&)> sig = &Print;
  return 0;
}

Why do I have to write template <typename T> class Signal;?

Why do I have to specify it ?


Solution

  • You're creating a specialization of Signal that combines the arbitrary types T and U into the form T(U). This is put together as the specialization Signal<T(U)>: only one type is in the parameter, which why we forward-declared the Signal taking only one type T. This wouldn't be possible without that declaration.

    Here's a simple example:

    template <typename T> struct A;
    
    template <typename T, typename U> struct A<T(U)> {
    
    };
    
    int main() {
    
        A<void(int)> a;
    
    }
    

    The types void and int are bound to the types T and U respectively. This is combined into the type void(int) used in the primary declaration of A to specialize the class.