🐭 函数模板与函数重载
在 C++ 中函数重载是一个比较重要的技术,重载决议本质上就是择优而选,但是当匹配程度相同时候,会优先选择一般函数而不是函数模板。而函数模板根据入参总是能实例化出最佳参数匹配的版本,因此,函数模板被选择的可能性很高,导致的误用也比较多。
上篇说到要避免设计重载使用通用引用参数的函数以及函数模板,那么目前能想到的主要替代解决方案如下,本文主要讲解其中的 4 和 5:
- 放弃重载,另写一个非重载函数
- 使用通用的 const T& 来绑定左值或者右值
- 按值传参类似 copy-and-swap 惯用法
- 使用 Tag dispatch 惯用法
- 使用 std::enable_if 来限制函数模板的实例化条件
🐂 Tag dispatch 与 if constexpr
在 C++ 中 Tag 分发是一种经典的模板条件实例化设计方式,C++17 以后我们可以使用 if constexpr 来使得这个设计方式更简单直观。
代码示例 : ```cppinclude
template
template
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; }
<a name="tv1Zr"></a>## 🐯 std::enable_if 与模板实例化我们可以使用 enable_if 来条件化的实例化一个函数模板,条件可以有多个,它们之间可以进行逻辑运算。条件不满足的时候,就像这个函数模板不存在一样,不会实例化。合理使用 if constexpr 同样可以简化 enable_if 设计方式。<br />**代码示例** :```cpp#include <iostream>// cast enum value to underlying type valuetemplate <typename T, std::enable_if_t<std::is_enum_v<std::decay_t<T>>, int> = 0>constexpr auto toUType(const T &e) noexcept {return static_cast<std::underlying_type_t<T>>(e);};// limit all type must be int// template<class... B> struct conjunction; - logical AND// template<class... B> struct disjunction; - logical OR// template<class B> struct negation; - logical negation// return type from std::enable_if_ttemplate <typename... Ts>std::enable_if_t<std::conjunction_v<std::is_same<int, std::decay_t<Ts>>...>, int>sum(Ts... args) {return (args + ...);}struct X {X(int x = 0) : x_(x){};int x_;};// factory method use enable_if_ttemplate <typename Concrete, typename... Ts>std::enable_if_t<std::is_constructible_v<Concrete, Ts...>, std::unique_ptr<Concrete>>constructArgs0(Ts &&... params) {return std::make_unique<Concrete>(std::forward<Ts>(params)...);}template <typename Concrete, typename... Ts>std::enable_if_t<!std::is_constructible_v<Concrete, Ts...>, std::unique_ptr<Concrete>>constructArgs0(Ts &&... params) {return nullptr;}// factory method use if constexprtemplate <typename Concrete, typename... Ts>std::unique_ptr<Concrete> constructArgs1(Ts &&... params) {if constexpr (std::is_constructible_v<Concrete, Ts...>) {return std::make_unique<Concrete>(std::forward<Ts>(params)...);} else {return nullptr;}}int main() {enum class CursorDirection : int { kLeft, kRight, kUp, kDown };std::cout << toUType(CursorDirection::kDown) << std::endl; // 3std::cout << sum(1, 2, 3, 4, 5, 6, 7, 8, 9) << std::endl; // 45auto x1 = constructArgs0<X>(42);auto x2 = constructArgs1<X>(42);std::cout << x1->x_ << ", " << x2->x_ << std::endl; // 42, 42auto x3 = constructArgs0<X>(42, 0);auto x4 = constructArgs1<X>(42, 0);assert(x3 == nullptr && x4 == nullptr);return 0;}
:::tips
- ‘std::enable_if’ 是 disable 掉了一些模板实例化版本,使得它们不存在,不参与重载决议
- ‘= delete’ 是 delete 掉了一些模板实例化版本,但它们还在,还会参与重载决议
- ‘std::enable_if’ 不能够被 ‘= delete’ 以及 ‘if constexpr’ 替代,它们的语义不一样 :::
我们使用 std::enable_if 来改进上篇文章中的模板类构造方法:
#include <iostream>#include <memory>#include <string>class Job {public:Job(const std::string &name) : name_{name} { std::cout << "call ctor1\n"; }template <typename T,std::enable_if_t<!std::is_base_of_v<Job, std::decay_t<T>>, int> = 0>Job(T &&name) : name_{std::forward<T>(name)} {std::cout << "call ctor2\n";}private:std::string name_;};int main() {// case 1: must match the const qualifierconst std::string name0{"j0"};Job j0(name0); // call ctor1std::string name1{"j1"};Job j1(name1); // call ctor2Job j2("j1"); // call ctor2// case 2: the template ctor// 1. does not prevents compiler to generate the copy ctor and move ctor// 2. it is typically better matches than copy constructors for non-const lvalues// 3. we can use the std::enable_if to disable same template instantiationJob j4 = j0; // calls the compiler generate copy ctorJob j5 = std::move(j0); // calls the compiler generate move ctorreturn 0;}
🐰 总结
- 理解通用引用函数重载的几种替代方案
- 理解使用 ‘if constexpr’ 来替代 tag dispatch 的方式
- 理解 std::enable_if 的应用以及它与 ‘= delete’ 和 ‘if constexpr’ 的区别
