Epoch
Epoch

Reputation: 190

Template specialization and function pointer

I have a structure templated and then i specialize it like the following :

template <class T>
struct FunctionSignature;

template <class Return, class Arg0>
struct FunctionSignature<Return (Arg0)>
{
    typedef Return(*type)(Arg0);
};

So I instanciate like this :

FunctionSignature<int (const std::string& str)>::type f = &onefunction;

The function onefunction have the following signature : int onefunction(const std::string &str) so this compile fine. Now my question is : is it possible to do what i have done without the first structure FunctionSignature ? I tried this but it doesn't compile :

template<class R (class U)>
struct A
{
  typedef R(*type)(U);
};

the instanciation :

A<int (const std::string &)>::type f = &onefunction;

I do this in c++03 in order to deepen my c++ understanding.

Upvotes: 1

Views: 1109

Answers (2)

John Cramerus
John Cramerus

Reputation: 169

That template is invalid. It has one type, an anonymous, non-type function pointer with return type R and takes an argument of type U. However, those types are ambiguous, so whenever the compiler tries to copy the code, it will fail. You can fix this in two ways.

template<class R, class U>
struct A {
  typedef R(*type)(U);
};

A<int, const std::string&>::type f = &onefunction;

Or if you wanted the non-type parameter

template<class R, class U, R(*type)(U)>
struct A {
     R g(U arg) {return type(arg);}
};

A<int, const std::string&, &onefunction> f;

Upvotes: 1

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

Now my question is : is it possible to do what i have done without the first structure FunctionSignature ?

No, it is not possible.

In order to make use of partial class template specialization you need to have a main class template you are going to specialize.

From partial specialization:

Syntax:

template < parameter-list > class-key class-head-name < argument-list> declaration

where class-head-name identifies the name of a previously declared class template.

Upvotes: 3

Related Questions