使用template参数可以传递链接列表的节点类型和数据类型



在我的链表类中,我想传递要作为模板参数存储的数据的dataType以及包含数据的节点类型,但我一直遇到编译错误。这是节点类llist.h

template<class itemType>
class Node {
itemType item{};
Node* next{};
Node* prev{};
public:
Node* getnext() { return next; }
Node* getprev() { return prev; }
itemType getitem() { return item; }
};

这是linkedlist类。llist.h

template <class itemType, class nodeType>
class LinkedList
{

//I am trying to say 
//using node=Node<itemType> 
//but dont want to use Node directly and want to get the type of Node from template argument
using node = nodeType<itemType>;        node* head{};
public:
node* getHead() { return head; }

};

当我尝试从main((实例化它时,我会得到编译器错误

int main()
{
std::cout << "Hello World!n";
LinkedList<int, Node<int> > list;
list.getHead();
}

以下是错误:

1>X:code1BlibBlibllist.h(16,23): error C2143: syntax error: missing ';' before '<'
1>C:codeBlibBlibllist.h(21): message : see reference to class template instantiation 'LinkedList<itemType,nodeType>' being compiled
1>C:codeBlibBlibllist.h(16,1): error C2059: syntax error: '<'
1>C:codeBlibBlibllist.h(16,1): error C2238: unexpected token(s) preceding ';'
1>Done building project "Blib.vcxproj" -- FAILED.

如果您想像nodeType<itemType>一样使用nodeType作为模板,可以将其声明为模板模板参数。

template <class itemType, template <typename> class nodeType>
class LinkedList

然后像一样使用

LinkedList<int, Node> list;

实时

如果您想像现在这样将其声明为类型模板参数,那么只需将其用作即可

template <class itemType, class nodeType>
class LinkedList
{
using node = nodeType;
...
};

实时

如果您有不同的节点类型,并且其中一些节点有额外的模板参数,那么模板模板参数方法就会出现问题。您也可以采用另一种方式,从Node中提取itemType类型,而不是显式地将其传递给LinkedList。这可以通过将decltype应用于Node:的成员函数来实现

template<class nodeType>
class LinkedList {
using itemType = std::decay_t<decltype(std::declval<nodeType>().getItem())>;
// ...
};

这里,std::decay_t用于从getItem()的返回类型中移除可能的引用。在您的特定示例中,它返回itemType,但一般情况下,我希望返回[const] itemType&

或者,我们可以在Node:中使用成员类型

template<class itemType>
class Node {
public:
using type = itemType;
};
template<class nodeType>
class LinkedList {
using itemType = typename nodeType::type;
// ...
};

现在可以写入LinkedList<Node<int>>并得到等于intitemType

最新更新