Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在模板函数(C+;+;)中将给定参数乘以3_C++_Function_Templates - Fatal编程技术网

C++ 在模板函数(C+;+;)中将给定参数乘以3

C++ 在模板函数(C+;+;)中将给定参数乘以3,c++,function,templates,C++,Function,Templates,我试图将给定的字符串乘以3,然后将其传递给模板函数 我收到错误消息: “initializing”无法从“T”转换为“std::basic_string”无论使用何种类型,它仍然需要编译。因此,如果您传递一个int,它将尝试为该字符串分配一个int,但失败 要像现在这样做一个类型测试,有几种方法。您可以创建适用于所有类型的默认模板版本,以及具有特定类型的非模板重载。如果适用,编译器将首选非模板重载: 模板 std::string by three(T参数){ 返回“不是字符串”; } std::

我试图将给定的字符串乘以3,然后将其传递给模板函数

我收到错误消息:
“initializing”无法从“T”转换为“std::basic_string”无论使用何种类型,它仍然需要编译。因此,如果您传递一个
int
,它将尝试为该字符串分配一个int,但失败

要像现在这样做一个类型测试,有几种方法。您可以创建适用于所有类型的默认模板版本,以及具有特定类型的非模板重载。如果适用,编译器将首选非模板重载:

模板
std::string by three(T参数){
返回“不是字符串”;
}
std::string by三(std::string参数){
返回参数+参数+参数;
}
您也可以专门化模板。您为特定类型的T提供“例外”:

模板
std::string by three(T参数){
返回“不是字符串”;
}
模板
std::string by三(std::string参数){
返回参数+参数+参数;
}
如果具有类型特征,可以使用
enable\u来启用具有特定特征的T类型:

template::type=0>
typename std::string by Three(T参数){
返回“不是字符串”;
}
模板
typename std::string by Three(T参数){
返回参数+参数+参数;
}
在C++17中,如果constexpr
在函数内部执行类型测试,则可以将类型特征和
结合起来,就像您尝试执行的那样:

模板
std::string by three(T参数){
如果constexpr(std::is_same_v){
返回参数+参数+参数;
}否则{
返回“不是字符串”;
}
}

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

此问题显示的代码不符合stackoverflow.com对。这意味着这里的任何人都不可能最终回答这个问题;但最多只能猜测。你的问题应该显示一个最小的例子,不超过一到两页的代码(“最小”部分),其他人可以剪切/粘贴、编译、运行和复制所描述的问题(“可复制”部分),完全如图所示(这包括任何辅助信息,如程序输入)。有关更多信息,请参阅。如何通过three调用
?我正在主函数中定义一个要传递的字符串。然后就按三下(绳子说)。
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;
  }
}