简体   繁体   中英

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.

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM