c++ - C++模板参数sizeof返回错误的结果

标签 c++ templates sizeof

这样,我可以找到数组中元素的数量。但是,当我将此int数组作为模板作为参数时,结果计算不正确

int arr[] = {1,2,3,4,5};
int size_arr  =  sizeof(arr) / sizeof(arr[0]);
我将INT数组作为类型模板的参数添加到列表中。
template <typename listType, typename arrayX>
 listType  addList(listType e , arrayX array)
{
     int        sizeOf = sizeof(array);
     int        sizeOfperOne = sizeof(array[0]);
     int        arrSize =  sizeOf   /   sizeOfperOne        ;
     cout << "Total Byte :  " << sizeOf << "     BytePerUnit : " << sizeOfperOne << " arrSize : " << arrSize<< endl;
     for (int i = 0; i <  arrSize; i++)
    {
        e.push_back(array[i]);
    }
    return e;
}
并创建了另一个模板和方法来打印此列表内容
template    <typename T>
void print(T& t, string name)
{
    typename T::iterator i = t.begin();
    cout << name << "\tMembers  ==>>>   ";
    while (i != t.end())
    {
        if (i == t.begin())
        {
            cout << *i++;
        }
        else
        {
            cout << " - " << *i++;
        }
    }
    cout << endl;
}
int main() 
{
    int mlArray[] = { 1,2,3,4,5};
    
    list<int>   MasterListe ;
    MasterListe = addList(MasterListe, mlArray);
    cout << "MasterListe SizeOf :    " << MasterListe.size() << endl;
    print(MasterListe, "MasterList      : ");
    return 0;
}

Total Byte : 8 BytePerUnit : 4 arrSize : 2


MasterListe SizeOf : 2
MasterList : Members ==>>> 1 - 2


数组用数字1,2,3,4,5填充,尽管传递了5个单位,但返回值为1和2。
我可能还想从下面的类中以INT类型创建当前正在使用的列表。
 list<TradeList> 
class TradeList
{
    public:
            int      PosTicket  ;
            strinh   Pairs      ;
            double   OpenPrice  ;
            double   StopLoss   ;
            double   TakeProfit ;
}
相信我,我无法通过研究找到解决方案。
非常感谢你的帮助。

最佳答案

主要问题是数组会衰减到指针,因此模板函数sizeof()中的addList值实际上正在尝试获取sizeof(int *)
如果addList所做的只是在std::list中添加项目,则有通用的方法可以执行此操作而无需创建另一个函数。
一种方法是使用std::copy_n:

#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
#include <string>

class TradeList
{
    public:
        int      PosTicket  ;
        std::string   Pairs      ;
        double   OpenPrice  ;
        double   StopLoss   ;
        double   TakeProfit ;
};

int main()
{
    TradeList mlArray[5];
    std::list<TradeList>   MasterListe;
    std::copy_n(mlArray, std::size(mlArray), std::inserter(MasterListe, MasterListe.end()));
    std::cout << MasterListe.size();
}
输出:
5

关于c++ - C++模板参数sizeof返回错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64840532/

相关文章:

.net - 无效 C++/CLI 的 ISO C++ 代码示例

python - Django 通过信号使模板缓存失效

c++ - 可以消除这个基类构造函数吗?

c - 在 C 中,sizeof 运算符在传递 2.5m 时返回 8 个字节,而在传递 1.25m * 2 时返回 4 个字节

c++ - 不同的运行时行为取决于程序的启动方式(终端与 Qt Creator)

C++ 错误 : <project_name> has triggered a breakpoint

c++ - 用 SWIG 包装模板模板参数类

c - sizeof(var) 在 C 语言中总是有效吗?

c++ - 什么是 sizeof(something) == 0?

c++ - OpenGL 2D 纹理无法正确显示 C++