简体   繁体   English

模板专业化和功能指针

[英]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. 函数onefunction具有以下签名: int onefunction(const std::string &str)因此可以正常编译。 Now my question is : is it possible to do what i have done without the first structure FunctionSignature ? 现在我的问题是:在没有第一个结构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. 我在c ++ 03中这样做是为了加深对c ++的理解。

Now my question is : is it possible to do what i have done without the first structure FunctionSignature ? 现在我的问题是:在没有第一个结构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. 其中class-head-name标识先前声明的类模板的名称。

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. 它具有一种类型,即返回类型为R的匿名非类型函数指针,并带有类型U的参数。但是,这些类型是模棱两可的,因此,每当编译器尝试复制代码时,它都会失败。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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