模板c++数组
template C++ array
我希望定义一个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
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '