2014-12-19 30 views
2
#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 
} 

为什么你不能在括号内使用字符串?有没有简单的方法来完成相同的任务,而无需声明字符串,然后创建节点,或者这是唯一的方法?为什么不能将字符串文字传递给使用模板参数的函数?

+3

因为'T'被推断为'const char *',并且'节点'和'节点'是不同的类型 – 2014-12-19 10:01:58

+2

我认为编译器给出的错误信息可以解释。 – starrify 2014-12-19 10:02:15

+3

如果你有C++ 14,你可以试试'“hi”s'。 – 2014-12-19 10:02:43

回答

7

T被推断为const char*,所以将返回Node<const char*>*,但你不能把它分配给Node<string>*

您可以创建一个临时的:

new_node(std::string("hi")); 

或者你可以拨打new_node有明确的资质:

new_node<std::string>("hi"); 
2

为什么不能将字符串文字传递给使用模板参数的函数?

你可以,你没有正确读取编译器错误信息。

这种精细编译:

new_node("hi"); 

但这并不:

Node<string>* root = new_node("hi"); //error! 

所以,问题显然不是传递字符串文字到模板的功能。