🐭 函数模板与函数重载

在 C++ 中函数重载是一个比较重要的技术,重载决议本质上就是择优而选,但是当匹配程度相同时候,会优先选择一般函数而不是函数模板。而函数模板根据入参总是能实例化出最佳参数匹配的版本,因此,函数模板被选择的可能性很高,导致的误用也比较多。
上篇说到要避免设计重载使用通用引用参数的函数以及函数模板,那么目前能想到的主要替代解决方案如下,本文主要讲解其中的 4 和 5:

  1. 放弃重载,另写一个非重载函数
  2. 使用通用的 const T& 来绑定左值或者右值
  3. 按值传参类似 copy-and-swap 惯用法
  4. 使用 Tag dispatch 惯用法
  5. 使用 std::enable_if 来限制函数模板的实例化条件

    🐂 Tag dispatch 与 if constexpr

    在 C++ 中 Tag 分发是一种经典的模板条件实例化设计方式,C++17 以后我们可以使用 if constexpr 来使得这个设计方式更简单直观。
    代码示例 : ```cpp

    include

template decltype(auto) typeInfoTagImpl0(T &&t, std::true_type) { std::cout << “typeInfoTagImpl0 intergral\n”; return std::forward(t); } template decltype(auto) typeInfoTagImpl0(T &&t, std::false_type) { std::cout << “typeInfoTagImpl0 non intergral\n”; return std::forward(t); } template decltype(auto) typeInfoTag0(T &&t) { return typeInfoTagImpl0(std::forward(t), std::is_integral>{}); }

template decltype(auto) typeInfoTag1(T &&t) { using T0 = std::decay_t; if constexpr (std::is_integral_v) { std::cout << “typeInfoTag1 intergral\n”; } else { std::cout << “typeInfoTag1 non intergral\n”; } return std::forward(t); }

int main() { // tag dispatch { auto t0 = typeInfoTag0(10); auto t1 = typeInfoTag0(“hello”); int i0 = 42; const volatile int &i1 = i0; typeInfoTag0(i1); } // if constexpr { [[maybe_unused]] auto t0 = typeInfoTag1(10); [[maybe_unused]] auto t1 = typeInfoTag1(“hello”); int i0 = 42; const volatile int &i1 = i0; typeInfoTag1(i1); }

return 0; }

  1. <a name="tv1Zr"></a>
  2. ## 🐯 std::enable_if 与模板实例化
  3. 我们可以使用 enable_if 来条件化的实例化一个函数模板,条件可以有多个,它们之间可以进行逻辑运算。条件不满足的时候,就像这个函数模板不存在一样,不会实例化。合理使用 if constexpr 同样可以简化 enable_if 设计方式。<br />**代码示例** :
  4. ```cpp
  5. #include <iostream>
  6. // cast enum value to underlying type value
  7. template <typename T, std::enable_if_t<std::is_enum_v<std::decay_t<T>>, int> = 0>
  8. constexpr auto toUType(const T &e) noexcept {
  9. return static_cast<std::underlying_type_t<T>>(e);
  10. };
  11. // limit all type must be int
  12. // template<class... B> struct conjunction; - logical AND
  13. // template<class... B> struct disjunction; - logical OR
  14. // template<class B> struct negation; - logical negation
  15. // return type from std::enable_if_t
  16. template <typename... Ts>
  17. std::enable_if_t<std::conjunction_v<std::is_same<int, std::decay_t<Ts>>...>, int>
  18. sum(Ts... args) {
  19. return (args + ...);
  20. }
  21. struct X {
  22. X(int x = 0) : x_(x){};
  23. int x_;
  24. };
  25. // factory method use enable_if_t
  26. template <typename Concrete, typename... Ts>
  27. std::enable_if_t<std::is_constructible_v<Concrete, Ts...>, std::unique_ptr<Concrete>>
  28. constructArgs0(Ts &&... params) {
  29. return std::make_unique<Concrete>(std::forward<Ts>(params)...);
  30. }
  31. template <typename Concrete, typename... Ts>
  32. std::enable_if_t<!std::is_constructible_v<Concrete, Ts...>, std::unique_ptr<Concrete>>
  33. constructArgs0(Ts &&... params) {
  34. return nullptr;
  35. }
  36. // factory method use if constexpr
  37. template <typename Concrete, typename... Ts>
  38. std::unique_ptr<Concrete> constructArgs1(Ts &&... params) {
  39. if constexpr (std::is_constructible_v<Concrete, Ts...>) {
  40. return std::make_unique<Concrete>(std::forward<Ts>(params)...);
  41. } else {
  42. return nullptr;
  43. }
  44. }
  45. int main() {
  46. enum class CursorDirection : int { kLeft, kRight, kUp, kDown };
  47. std::cout << toUType(CursorDirection::kDown) << std::endl; // 3
  48. std::cout << sum(1, 2, 3, 4, 5, 6, 7, 8, 9) << std::endl; // 45
  49. auto x1 = constructArgs0<X>(42);
  50. auto x2 = constructArgs1<X>(42);
  51. std::cout << x1->x_ << ", " << x2->x_ << std::endl; // 42, 42
  52. auto x3 = constructArgs0<X>(42, 0);
  53. auto x4 = constructArgs1<X>(42, 0);
  54. assert(x3 == nullptr && x4 == nullptr);
  55. return 0;
  56. }

:::tips

  1. ‘std::enable_if’ 是 disable 掉了一些模板实例化版本,使得它们不存在,不参与重载决议
  2. ‘= delete’ 是 delete 掉了一些模板实例化版本,但它们还在,还会参与重载决议
  3. ‘std::enable_if’ 不能够被 ‘= delete’ 以及 ‘if constexpr’ 替代,它们的语义不一样 :::

我们使用 std::enable_if 来改进上篇文章中的模板类构造方法:

  1. #include <iostream>
  2. #include <memory>
  3. #include <string>
  4. class Job {
  5. public:
  6. Job(const std::string &name) : name_{name} { std::cout << "call ctor1\n"; }
  7. template <typename T,
  8. std::enable_if_t<!std::is_base_of_v<Job, std::decay_t<T>>, int> = 0>
  9. Job(T &&name) : name_{std::forward<T>(name)} {
  10. std::cout << "call ctor2\n";
  11. }
  12. private:
  13. std::string name_;
  14. };
  15. int main() {
  16. // case 1: must match the const qualifier
  17. const std::string name0{"j0"};
  18. Job j0(name0); // call ctor1
  19. std::string name1{"j1"};
  20. Job j1(name1); // call ctor2
  21. Job j2("j1"); // call ctor2
  22. // case 2: the template ctor
  23. // 1. does not prevents compiler to generate the copy ctor and move ctor
  24. // 2. it is typically better matches than copy constructors for non-const lvalues
  25. // 3. we can use the std::enable_if to disable same template instantiation
  26. Job j4 = j0; // calls the compiler generate copy ctor
  27. Job j5 = std::move(j0); // calls the compiler generate move ctor
  28. return 0;
  29. }

🐰 总结

  1. 理解通用引用函数重载的几种替代方案
  2. 理解使用 ‘if constexpr’ 来替代 tag dispatch 的方式
  3. 理解 std::enable_if 的应用以及它与 ‘= delete’ 和 ‘if constexpr’ 的区别