C++:将字符串传递给模板。
没有指定什么类型的数据类型 int 工作正常,但是当我们将字符串传递给模板时,我们在这里面临错误,你能帮我解决这个问题吗?
template <Typename T>
T add(T a,T b)
{
return a+b;
}
int main() {
int res = add(2,5); // this is execute perfctly.
string str = add("hello","world"); // here i am getting eror for passing directly string, can we fix this issue without specifying what data type we are passing.
return 0;
}
最佳答案
我猜你认为你正在将 std::string
传递给 add
,但你不是。您正在传递 const char *
。您不能使用两个字符指针调用 +
。
如果您改为传递两个 std::string,则可以用它们调用 +
。
#include <string>
using namespace std::string_literals;
template <typename T>
T add(T a,T b)
{
return a+b;
}
int main() {
int res = add(2,5); // this is execute perfctly.
std::string str = add("hello"s,"world"s); // the s on the end makes it a std::string.
// this is the same as the line above
std::string str2 = add(std::string("hello"), std::string("world"));
return 0;
}
关于c++ - 将直接字符串传递给 C++ 中的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52069300/