c++ - 将直接字符串传递给 C++ 中的模板

标签 c++ string templates

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;
}

https://godbolt.org/z/kSqs2l

关于c++ - 将直接字符串传递给 C++ 中的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52069300/

相关文章:

swift - 如何将字符串换行为 72 个字符

templates - 如何为登录页面定义一个模板/ View /任何内容,但为其他页面定义默认模板/ View /任何内容

c++ - 根据模板参数选择函数名

c++ - 类类型错误

c++ - 创建 mwArray 的问题

c++ - 图形到图形深度依赖性,深度缓冲区被破坏

c++ - 将 CMake 与 LLVM 一起使用时出错

c++ - boost::lockfree::stack 可以安全地接受字符串指针吗?

转换字符串时间戳 HH :MM:SS to an integer in C

c++ - 关联容器所需的比较器