#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 *',并且'节点'和'节点'是不同的类型 –
2014-12-19 10:01:58
我认为编译器给出的错误信息可以解释。 – starrify 2014-12-19 10:02:15
如果你有C++ 14,你可以试试'“hi”s'。 – 2014-12-19 10:02:43