简体   繁体   English

如何使一个通用的函数适用于各种高度相似的类型?

[英]How to make a function generic for various, highly similar types?

I have a linked list format that is of various types ( int , double , for instance): 我有各种类型的链表格式(例如intdouble ):

struct DblNode {
    double value;
    DblNode * next;
}
struct IntNode {
    int value;
    IntNode * next;
}

And now I am doing things to these lists, and I run into the issue that I am constantly copying and pasting functions, making minor type edits: 现在,我正在处理这些列表,并且遇到了不断复制和粘贴函数,进行较小的类型编辑的问题:

DblNode * dbl_listind(DblNode * head,int ind){
    DblNode * position = head;
    int counter = 0;
    while(counter < ind){
        position = position -> next;
        counter++;
    }
    return position;
}

And then duplicating for int . 然后复制int

Is there a way to somehow have a generalized list type, and then somehow specify this functionality, independent of the type of the value member of my linked list? 有没有办法以某种方式具有广义列表类型,然后以某种方式指定此功能,而与链接列表的值成员的类型无关?

That's what class/function templates supposed to do. 那就是类/函数模板应该做的。 eg 例如

template <typename T>
struct Node {
    T value;
    Node * next;
}

template <typename T>
Node<T> * listind(Node<T> * head,int ind){
    Node<T> * position = head;
    int counter = 0;
    while(counter < ind){
        position = position -> next;
        counter++;
    }
    return position;
}

// optional
using DblNode = Node<double>;
using IntNode = Node<int>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将各种类型的function指针存储在一起? - How to store various types of function pointers together? 如何在宏 function arguments 中使用泛型类型 - How to use generic types in macro function arguments 如何针对程序相似的不同数据类型特化模板function? - How to specialize a template function for different data types in which the procedures are similar? 如何在C ++中使通用的stringToVector函数? - How to make generic stringToVector function in c++? 如何使函数采用通用向量? - How to make function take in generic vector? Visual Studio C++ 智能感知 Function 信息 - 如何解释各种分隔符、类型和首字母缩略词 - Visual Studio C++ intellisense Function Info - How to interpret the various delimiters, types, and acronyms 如何将 shared_ptr 提供给模板 function,该模板将向向量添加各种数据类型? - How to feed a shared_ptr to a template function that shall add various data types to a vector? 如何定义采用最通用数量和参数类型的函数 - How to define function that takes the most generic number and types of parameters 如何将各种类型的函数作为容器进行管理 - How to manage various types of functions as containers 基于typedef定义的相似类型的函数重载 - function overload based on typedef defined similar types
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM