【发布时间】:2021-10-30 09:08:50
【问题描述】:
以下运行正常:
#include <iostream>
#include <string>
/**
* Simply print the value of the argument and adapt the
* statement based on its type.
*/
template<typename T>
int function(T value){
if(std::is_same<T,double>() || std::is_same<T,float>()){
std::cout << value << ", type is float" << std::endl;
return 0;
}
else if(std::is_same<T,std::string>()){
std::cout << value << ", type is string" << std::endl;
return 0;
}
else if(std::is_same<T,char*>() || std::is_same<T,const char*>()){
std::cout << value << ", type is char*" << std::endl;
return 0;
}
else{
std::cout << "Unsupported data type" << std::endl;
return -1;
}
}
int main(){
function<double>(1.2345);
function<std::string>("Hello World");
const char* sentence = "Hello World"; function<const char*>(sentence);
return 0;
}
由于运行没有任何问题,我尝试更改以下行:
std::cout << value << ", type is string" << std::endl;
到
std::cout << value.c_str() << ", type is string" << std::endl;
但是这不会编译。就像在编译 .c_str() 调用时定义了 value 的类型一样。但是,我预计value 参数的类型仅取决于模板参数T。为什么在这种情况下不编译?
产生以下错误:
In instantiation of ‘int function(T) [with T = double]’:
.cpp:321:25: required from here
error: request for member ‘c_str’ in ‘value’, which is of non-class type ‘double’
std::cout << value.c_str() << ", type is string" << std::endl;
~~~~~~^~~~~
In instantiation of ‘int function(T) [with T = const char*]’:
.cpp:323:70: required from here
.cpp:306:22: error: request for member ‘c_str’ in ‘value’, which is of non-class type ‘const char*’
【问题讨论】:
-
为什么要这样?你传递了
const char*,它没有.c_str()函数。你也通过了double,这同样不符合这个要求 -
您可能正在寻找
if constexpr。 “正常”if在运行时检查其状况;所有分支都必须编译,即使实际上只使用了一个。 -
为了完整起见,
std::string和const char*都应该被处理。问题出在std::string案例上。 -
@Lala5th,您能详细说明一下吗?我的问题是为什么它不应该编译?我错过了什么?
-
@LoW Igor 在他们的评论中很好地解释了这一点