首页 > 解决方案 > 将不同的变量传递给模板函数

问题描述

我有一个为 2 个变量分配一些值的函数: bool get(int& value1, string& value2);

我需要使用这些返回的变量之一调用模板函数。我该怎么做?

bool get(int& value1, string& value2) { /* assign them */ };

template<typename T>
doWork(const T& value) { /* do some work */ };

template<typename T>
void foo() {
  int value1;
  string value2;
  get(value1, value2);
  while(doWork(/*if T == int, pass value1, otherwise value2*/)) {
    // do smth
  }
};

标签: c++templates

解决方案


您可以将if constexpr(C++17 起) 与std::is_same(from <type_traits>) 一起使用。当您想在循环条件中使用它时,我将它包装在一个 lambda 中:

template<typename T>
void foo() {
  int value1;
  string value2;
  get(value1, value2);
  auto doWorkIntOrString = [&](){
      if constexpr (std::is_same_v<int,T>) return doWork(value1);
      else return doWork(value2);
  };
  while(doWorkIntOrString()) {
    // do smth
  }
};

推荐阅读