How does Stroustrup's Can_Copy template work?

后端 未结 4 690
野趣味
野趣味 2020-12-19 08:49

Stroustrup provides a Can_copy template. How does it work?

template struct Can_copy {
    static void constraints(T1 a, T2 b) { T2          


        
4条回答
  •  星月不相逢
    2020-12-19 09:08

    The usage of the template is as simple as Can_copy();

    If an instance of T1 cannot be copied to an instance of T2, the code b = a wouldn't compile at all. The same way, if an instance of T2 cannot be initialized with the instance of T1, the code T2 c = a; wouldn't compile.

    So, if T1 cannot be copied to T2, the line containing the template usage won't compile.

    The whole construct produces (almost) no code, and is easily removed by the optimizer.

提交回复
热议问题