天天看点

第十六章 16.2.2节练习

练习16.37

标准库max函数有两个参数,它返回实参中的较大者。此函数有一个模板类型参数。你能再调用max时传递给它一个int和一个double吗?如果可以,如何做?如果不可以,为什么?

解答:

default (1)
template <class T> constexpr const T& max (const T& a, const T& b);
      
custom (2)
template <class T, class Compare>
  constexpr const T& max (const T& a, const T& b, Compare comp);
      
initializer list (3)
template <class T> constexpr T max (initializer_list<T> il);
template <class T, class Compare>
  constexpr T max (initializer_list<T> il, Compare comp);      

以上是max的三个声明。

当传递给它一个int和一个double的,T会无法确定类型,所以肯定会在编译的时候出现错误。

练习16.38

当我们调用make_shared(参见12.1.1节,第401行)时,必须提供一个显示模板实参。解释为什么需要显示模板实参以及它是如何使用的。

解答:

这个其实就是定义的问题,603页和604页,或者说这节都在回答这个问题。

练习16.39

对16.1.1节(第578页)中的原始版本的compare函数,使用一个显示模板实参,使得可以向函数传递两个字符传字面常量。

解答:

compare<std::string>("hello", "world")
           

继续阅读