将函数指针非类型模板参数转换为类型模板参数

use*_*066 6 c++ templates

以下示例代码在gcc下编译并按我希望的方式工作.它允许我使用函数定义作为模板参数来实例化一个对象,但是该类能够使用函数中的不同类型,就像它们作为类型模板参数单独传递一样.

template<class FuncSignature> class Obj;

template<class Type1, class Type2> class Obj<Type1 (Type2)>
{
public:
  Type1 var1;
  Type2 var2;
};

int main(int argc, char **argv)
{
  Obj<char (int)> A;
  A.var1 = 'a';
  A.var2 = 3;
}
Run Code Online (Sandbox Code Playgroud)

即使它似乎工作,我不知道这个代码是做什么的.为什么这段代码有效并且符合C++标准?

Unc*_*ens 7

它为什么不起作用?实例化匹配特化,它将复合类型(函数)的组件类型(charint)提取char(int)Type1Type2.

顺便说一句,您没有非类型模板参数.函数类型是一种类型.如果您有一个非类型模板参数,那么它将如下所示:

template <char(int)>
struct X {};

char foobar(int);

int main()
{
    X<foobar> x;
}
Run Code Online (Sandbox Code Playgroud)

或完全模板化:

template <class R, class A, R(A)>
//                          ^^^^
//                      non-type parameter
struct X {};

char foobar(int);

int main()
{
    X<char, int, foobar> x;
//               ^^^^^^
//   a specific function, not type
}
Run Code Online (Sandbox Code Playgroud)

  • 我在这里感觉到混乱的根源:"一个功能是一种类型." 那不是真的.只有你知道这些事情,你才能推断出这句话的含义.为了减少混淆的来源,更准确地说"函数类型是一种类型.".同样,整数不是一种类型.但整数类型是.同样地,提问者可能会混淆自己说"它允许我用函数定义实例化一个对象作为模板参数" - 该语句没有任何意义. (2认同)