为什么不能将字符串文本传递给使用模板参数的函数?
Why can't you pass a string literal to a function that uses a template argument?
#include<iostream>
#include<string>
using namespace std;
template<typename T>
struct Node{
T data;
Node* left;
Node* right;
Node(T x) : data(x), left(NULL), right(NULL){}
};
template<typename T>
Node<T>* new_node(T x)
{
Node<T>* return_node = new Node<T>(x);
return return_node;
}
int main()
{
Node<string>* root = new_node("hi"); //error!
string x = "hi";
Node<string>* root2 = new_node(x); //OK
}
为什么不能在括号内使用字符串文字?是否有任何简单的方法可以在不声明字符串然后创建节点的情况下完成相同的任务,或者这是唯一的方法?
T
被推导为const char*
,因此将返回Node<const char*>*
,但你不能将其分配给Node<string>*
您可以创建临时:
new_node(std::string("hi"));
或者,您可以使用显式限定调用new_node
:
new_node<std::string>("hi");
为什么不能将字符串文本传递给使用模板参数的函数?
您可以,您没有正确阅读编译器错误消息。
这编译得很好:
new_node("hi");
但这不会:
Node<string>* root = new_node("hi"); //error!
因此,问题显然不是将字符串文本传递给模板函数。
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类