【问题标题】:Multiply given argument by 3 within a template function (C++) [closed]在模板函数(C++)中将给定参数乘以 3 [关闭]
【发布时间】:2025-12-26 17:25:06
【问题描述】:

我正在尝试将给定的字符串“乘以”3 - 这将传递给模板函数。

我收到错误消息: 'initializing' 不能从 'T' 转换为 'std::basic_string

template <typename T>
std::string bythree(T argument) {

  std::string message = "";
  
  if (typeid(argument) == typeid(std::string)) {
    std::string mul_str = argument + argument + argument;
    message = mul_str;
  }
}

当我使用std::string message = argument + argument + argument;的逻辑时,我得到了这个

非常感谢任何有关在此背后使用的逻辑的帮助。

【问题讨论】:

  • 此问题显示的代码不符合 *.com 对 minimal reproducible example 的要求。这意味着这里的任何人都不太可能最终回答这个问题。但最多只能猜测。你应该edit你的问题来展示一个最小的例子,不超过一两页代码(“最小”部分),其他人都可以剪切/粘贴、编译、运行和重现所描述的问题(“ reproducible”部分)完全如图所示(这包括任何辅助信息,例如程序的输入)。请参阅How to Ask 了解更多信息。
  • 你怎么打电话给bythree
  • 我在我的主函数中定义了一个我想要传递的字符串。然后只需计算三个(所说的字符串)。

标签: c++ function templates


【解决方案1】:

无论你使用什么类型,它仍然需要编译。所以,如果你传递一个int,它会尝试给那个字符串分配一个int并且失败。

要像您一样进行类型测试,有几种方法。您可以创建适用于所有类型的默认模板版本,以及具有您特定类型的非模板重载。编译器会在适用时更喜欢非模板重载:

template <typename T>
std::string bythree(T argument) {
  return "not a string";
}

std::string bythree(std::string argument) {
  return argument + argument + argument;
}

您也可以改为专门化模板。您为特定类型的 T 提供“例外”:

template <typename T>
std::string bythree(T argument) {
  return "not a string";
}

template<>
std::string bythree<std::string>(std::string argument) {
  return argument + argument + argument;
}

您可以将enable_if 与类型特征一起使用以启用具有特定特征的 T 类型:

template <typename T, typename std::enable_if<!std::is_same<T, std::string>::value, int>::type = 0>
typename std::string bythree(T argument) {
  return "not a string";
}

template <typename T, typename std::enable_if<std::is_same<T, std::string>::value, int>::type = 0>
typename std::string bythree(T argument) {
  return argument + argument + argument;
}

在 C++17 中,您可以结合类型特征和 if constexpr 在函数内进行类型测试,就像您尝试做的那样:

template <typename T>
std::string bythree(T argument) {
  if constexpr (std::is_same_v<T, std::string>) {
    return argument + argument + argument;
  } else {
    return "not a string";
  }
}

这适用于 typeid(T) == typeid(std::string) 不适用的情况,因为如果条件不成立(在编译时评估),编译器不会尝试编译 if constexpr 块的内容。

【讨论】: