以下示例代码在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++标准?
它为什么不起作用?实例化匹配特化,它将复合类型(函数)的组件类型(char和int)提取char(int)为Type1和Type2.
顺便说一句,您没有非类型模板参数.函数类型是一种类型.如果您有一个非类型模板参数,那么它将如下所示:
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)
| 归档时间: |
|
| 查看次数: |
990 次 |
| 最近记录: |