04 可变模板参数

2021-05-21  本文已影响0人  奇点创客

可变参数模板示例

void print() {} // 没有参数时将调用此函数

template<typename T, typename... Types>
void print(T firstArg, Types... args)
{
  std::cout << firstArg << ' ';  // 打印第一个实参,无参数时将调用此函数
  print(args...); // 调用print()打印其余实参
}

int main()
{
  std::string s("world");
  print(3.14, "hello", s); // 3.14 hello world
}

重载可变参数和非可变参数模板

template<typename T>
void print(T x)
{
  std::cout << x << ' ';
}

template<typename T, typename... Types>
void print(T firstArg, Types... args)
{
  print(firstArg);
  print(args...);
}

sizeof...运算符

template<typename T, typename... Types>
void print(T firstArg, Types... args)
{
  std::cout << sizeof...(Types) << '\n'; // print number of remaining types
  std::cout << sizeof...(args) << '\n'; // print number of remaining args
}
template<typename T, typename... Types>
void print(T firstArg, Types... args)
{
  std::cout << firstArg << '\n';
  if (sizeof...(args) > 0) // sizeof...(args)==0时会出错
  {
    print(args...); // 因为print(args...)仍将被初始化,而此时没有实参
  }
}
template<typename T, typename...Types>
void print(const T& firstArg, const Types&... args)
{
  std::cout << firstArg << '\n';
  if constexpr (sizeof...(args) > 0)
  {
    print(args...); // 只在sizeof...(args) > 0时实例化
  }
}

折叠表达式

template<typename... T>
auto foldSum(T... s)
{
  return (... + s);   // ((s1 + s2) + s3) ...
}
foldSum(1, 2, 3, 4, 5); // 假如实参是12345
// 左边是返回值,右边是计算时的内部展开方式
(... + s):((((1 + 2) + 3) + 4) + 5)
(s + ...):(1 + (2 + (3 + (4 + 5))))
(0 + ... + s):(((((0 + 1) + 2) + 3) + 4) + 5)
(s + ... + 0):(1 + (2 + (3 + (4 + (5 + 0)))))
struct Node {
  int val;
  Node* left;
  Node* right;
  Node(int i = 0) : val(i), left(nullptr), right(nullptr) {}
};

// 使用operator->*的折叠表达式,用于遍历指定的二叉树路径
template<typename T, typename... Ts>
Node* traverse(T root, Ts... paths)
{
  return (root ->* ... ->* paths); // np ->* paths1 ->* paths2 ...
}

int main()
{
  Node* root = new Node{ 0 };
  root->left = new Node{ 1 };
  root->left->right = new Node{ 2 };
  root->left->right->left = new Node{ 3 };

  auto left = &Node::left;
  auto right = &Node::right;
  Node* node1 = traverse(root, left);
  std::cout << node1->val; // 1
  Node* node2 = traverse(root, left, right);
  std::cout << node2->val; // 2
  Node* node3 = traverse(node2, left);
  std::cout << node3->val; // 3
}
template<typename... Ts>
void print(const Ts&... args)
{
  (std::cout << ... << args) << '\n';
}
template<typename T>
class AddSpace {
 public:
  AddSpace(const T& r): ref(r) {}
  friend std::ostream& operator<<(std::ostream& os, AddSpace<T> s)
  {
    return os << s.ref << ' ';   // 输出传递的实参和一个空格
  }
 private:
  const T& ref; // 构造函数中的实参的引用
};

template<typename... Args>
void print(Args... args)
{
  (std::cout << ... << AddSpace(args)) << '\n';
}

可变参数模板的应用

auto p = std::make_shared<std::complex<double>>(3.14, 4.2);
void f(int, std::string);
std::thread t(f, 42, "hi");
struct A {
  A(int _i, std::string _s) : i(_i), s(_s) {}
  int i;
  std::string s;
};

std::vector<A> v;
v.emplace_back(1, "hi");
namespace std {
template<typename T, typename... Args>
shared_ptr<T> make_shared(Args&&... args);

class thread {
 public:
  template<typename F, typename... Args>
  explicit thread(F&& f, Args&&... args);  
  ...
};

template<typename T, typename Allocator = allocator<T>>
class vector {
 public:
  template<typename... Args>
  reference emplace_back(Args&&... args);
  ...
};
}

可变参数表达式(Variadic Expression)

template<typename... Args>
void print(const Args&... args)
{
  (std::cout << ... << args);
}

template<typename... T>
void printDoubled(const T&... args)
{
  print(args + args...);
}

int main()
{
  printDoubled(3.14, std::string("hi"), std::complex<double>(4, 2));
  // 等价于
  print(3.14 + 3.14, std::string("hi") + std::string("hi"),
    std::complex<double>(4, 2) + std::complex<double>(4, 2));
}
template<typename... T>
void addOne(const T&... args)
{
  print(args + 1...); // 错误 1...是带多个小数点的字面值,不合法
  print(args + 1 ...); // OK
  print((args + 1)...); // OK
}
template<typename T1, typename... TN>
constexpr bool isHomogeneous(T1, TN...)
{ // 判断是否所有实参类型相同
  return (std::is_same_v<T1, TN> && ...); // since C++17
}

isHomogeneous(1, 2, "hi"); // 结果为false
// 扩展为std::is_same_v<int, int> && std::is_same_v<int, const char*>
isHomogeneous("hello", "", "world", "!") // 结果为true:所有实参都为const char*

可变参数索引(Variadic Index)

template<typename... Args>
void print(const Args&... args)
{
  (std::cout << ... << args);
}

template<typename C, typename... N>
void printElems(const C& c, N... n)
{ 
  print(c[n]...);
}

int main()
{
  std::vector<std::string> v{ "good", "times", "say", "bye" };
  printElems(v, 2, 0, 3); // say good bye:等价于print(v[2], v[0], v[3]);
}
template<std::size_t... N, typename C>
void printIdx(const C& c)
{
  print(c[N]...);
}

std::vector<std::string> v{ "good", "times", "say", "bye" };
printIdx<2, 0, 3>(v);

可变参数类模板(Variadic Class Template)

template<class... Types>
class tuple;
 
tuple<int, std::string, char> t;
template<class... Types>
class variant;

variant<int, std::string, char> v;
template<std::size_t...>
struct Indices
{};

template<typename... Args>
void print(const Args&... args)
{
  (std::cout << ... << args);
}

template<typename T, std::size_t... N>
void printByIdx(T t, Indices<N...>)
{
  print(std::get<N>(t)...);
}

int main()
{
  std::array<std::string, 5> arr{ "Hello", "my", "new", "!", "World" };
  printByIdx(arr, Indices<0, 4, 3>()); // HelloWorld!

  auto t = std::make_tuple(12, "monkeys", 2.0);
  printByIdx(t, Indices<0, 1, 2>()); // 12monkeys2
}

可变参数推断指南(Variadic Deduction Guide)

namespace std {
template<typename T, typename... U> array(T, U...)
  -> array<enable_if_t<(is_same_v<T, U> && ...), T>, (1 + sizeof...(U))>;
}

可变参数基类(Variadic Base Class)与using

class A {
 public:
  A(const std::string& x) : s(x) {}
  auto f() const { return s; }
 private:
  std::string s;
};

struct A_EQ {
  bool operator() (const A& lhs, const A& rhs) const
  {
    return lhs.f() == rhs.f();
  }
};

struct A_Hash {
  std::size_t operator() (const A& a) const
  {
    return std::hash<std::string>{}(a.f());
  }
};

// 定义一个组合所有基类的operator()的派生类
template<typename... Bases>
struct Overloader : Bases...
{
  using Bases::operator()...;  // OK since C++17
}; 

int main()
{
  // 将A_EQ和A_Hash组合到一个类型中
  using A_OP = Overloader<A_Hash, A_EQ>;

  /* unordered_set的声明
  template<
      class Key,
      class Hash = std::hash<Key>,
      class KeyEqual = std::equal_to<Key>,
      class Allocator = std::allocator<Key>
  > class unordered_set;
  */

  std::unordered_set<A, A_Hash, A_EQ> s1;
  std::unordered_set<A, A_OP, A_OP> s2;
}
上一篇下一篇

猜你喜欢

热点阅读