Stroustrup的Can_Copy模板如何工作? [英] How does Stroustrup's Can_Copy template work?

查看:62
本文介绍了Stroustrup的Can_Copy模板如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Stroustrup提供了一个 Can_copy模板

Stroustrup provides a Can_copy template. How does it work?

template<class T1, class T2> struct Can_copy {
    static void constraints(T1 a, T2 b) { T2 c = a; b = a; }
    Can_copy() { void(*p)(T1,T2) = constraints; }
};

尤其是为什么他需要行 void(* p)( T1,T2)=约束; 而不是空的构造函数?

In particular, why does he need the line void(*p)(T1,T2) = constraints; instead of an empty constructor? Are compilers allowed to produce only the functions a particular template instance uses as an optimisation?

推荐答案

是因为在模板中未使用成员函数,所以编译器只允许生成特定模板实例用作优化的函数吗?在生成的代码中不存在,因此要检查约束,您必须在某处显式调用 constraints()

It's because not used member functions in templates don't exist in generated code, so to check constrainst you would have to call constraints() explicitly somewhere.

这样会生成 constraints()的代码,因此可以在编译时检查约束(即可以复制)的目的。

This way code for constraints() is generated, so constraints are checked in compile time (and that is the purpose of Can_copy).

这篇关于Stroustrup的Can_Copy模板如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆