c++ - 了解用户自定义函数

标签 c++ templates user-defined-functions

创建一个位字段的 UserArray,可以声明如下:我们的数组占用的大小将小于普通数组。假设我们想要一个包含 20 个标志 (TRUE/FALSE) 的数组。 bool FLAG[20]将占用 20 个字节的内存,而 UserArray<bool,bool,0,20>将占用 4 个字节的内存。

  • 使用类模板创建用户数组。
  • 使用位运算符来打包数组。
  • 平等经营也要落实。

    template<class T,int W,int L,int H>//i have used template<class T> 
                                       //but never used such way
    class UserArray{ 
            //....                 
    };        
    typedef UserArray<bool,4,0,20> MyType;
    

哪里:

  • T = 数组元素的类型
  • W = 数组元素的宽度,0 < W < 8
  • L = 数组索引的下限(最好为零)
  • H = 数组索引的上限

主程序:

int main() {
      MyType Display;  //typedef UserArray<T,W,L,H> MyType; defined above

      Display[0] = FALSE; //need to understand that how can we write this?
      Display[1] = TRUE; //need to understand that how can we write this?

      //assert(Display[0]);//commented once, need to understand above code first
      //assert(Display[1]);//commented once..
      //cout << “Size of the Display” << sizeof(Display);//commented once..
}

我的疑问是这些参数如何,即 T,L,W & H在类里面使用 UserArray以及我们如何编写 UserArray 的实例作为Display[0] & Display[1]它代表什么?

类似类型的简短示例对我来说很容易理解。

最佳答案

W , LH非类型模板参数。您可以使用常量值实例化模板(在编译时),例如:

template <int N>
class MyArray
{
public:
    float data[N];

    void print() { std::cout << "MyArray of size " << N << std::endl; }
};

MyArray<7> foo;
MyArray<8> bar;

foo.print();  // "MyArray of size 7"
bar.print();  // "MyArray of size 8"

在上面的例子中,到处都是N出现在模板定义中,它将在编译时被提供的常量替换。

请注意 MyArray<7>MyArray<8>就编译而言,它们是完全不同的类型。

我不知道您的具体问题的解决方案是什么。但是您的代码目前无法编译,因为您没有为模板参数提供值。

关于c++ - 了解用户自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6691560/

相关文章:

c++ - 在链表中插入 'n' 节点并打印其数据(C++)

c++ - 如何获取程序路径

c++ - 模板化函数指针

c++ - 我需要帮助在 C++ 中创建优先级队列

c++ - 初始化通用模板化容器

c# - 如何从另一个工作表中获取单元格值并将其分配给 UDF 的返回值?

C++ OpenGL 相机运动

php - 如何从 PHP 代码中调用 MySQL 存储过程?

sql - 带有 OUT 参数的 PostgreSQL 函数和带有 TABLE 结果的 PostgreSQL 函数之间有任何形式上的区别吗?

c++ - 如何在 C++ 中并排显示两个函数?