模板c++数组

template C++ array

本文关键字:数组 c++ 模板      更新时间:2023-10-16

我希望定义一个String类型,使得声明一个String类型的变量在编译时等同于char[N]。我曾见过一些特定数组维度的模板函数的例子,但没有一个是用来处理实际的具体类型的。

namespace myns {
   typedef uint32_t LongCount;
   typedef uint16_t ShortCount;
   typedef uint32_t LongDist;
   typedef uint16_t ShortDist;
   #define LONG_NAME 20;
   #define SHORT_NAME 10;
   // this would be better in my opinion:
   typedef String<20> LongName;
   typedef String<10> ShortName;

template<typename DIST1, typename DIST2, typename COUNT1>
struct SomeStruct1Base
{
   DIST1 dist1;
   DIST2 dist2;
   COUNT1 c;
};
typedef SomeStruct1Base<LongDist, LongDist, LongCount> SomeStruct1Long;
typedef SomeStruct1Base<ShortDist, ShortDist, ShortCount> SomeStruct1Short;
template<typename DIST1, typename COUNT1, int NAME_LEN>
struct SomeStruct2Base
{
   DIST1 dist1;
   uint32_t distx;
   COUNT1 c;
   char   name[NAME_LEN];
};
typedef SomeStruct2Base<LongDist, LongCount, SHORT_NAME> SomeStruct2Long;
typedef SomeStruct2Base<LongDist, LongCount, SHORT_NAME> SomeStruct2Short;
typedef SomeStruct2Base<LongDist, LongCount, LONG_NAME> SomeStruct2Ext;
上面的

不是很一致,我认为最好传入String<6>或其他参数,而不是传递int形参给模板。没有?

更新:我使用此结构来解析在char缓冲区中表示的网络数据,因此该结构需要能够执行reinterpret_cast<>able。很抱歉我之前没有提到这一点,但我现在提到了,因为我看到一些建议在这种情况下会失效。

在模板中使用std::size_t参数,然后提供operator char*的重载。这样的:

template <std::size_t N>
class String {
  public:
    operator char*()
    {
        return data;
    }
  private:
    char data[N];
};

有些人认为operator char*(和其他隐式转换操作符)不好,他们可能是对的。在确定使用它之前,您应该真正了解使用它的危险,因为它并不总是最好的主意。

可以使用以下结构体:

template<unsigned int SIZE>
struct String { typedef char t[SIZE]; };

用法:

int main ()
{
  char a[20];
  String<20>::t b;
  //sizeof(a) = sizeof(b); both are equivalent
}

事实上,你可以让它泛化到任何类型:

template<typename T, unsigned int SIZE>
struct MyArray { typedef T t[SIZE]; };

您可以添加operator=以允许更酷的分配:

template <size_t N>
class String {
  public:
    operator char*()
    {
        return data;
    }
    String& operator=(char* const &rhs)
    {
        strcpy_s(data, N, rhs);
        return *this;
    }
  private:
    char data[N];
};
int main()
{
    String<20> str;
    // You can do this:
    str = "This can be done";
    String<40> another;
    // And this:
    another = str;
    // ... and this:
    another = str = "Ciao";
}

注意您应该使用strcpy_s