大小数组作为C ++中的函数参数类型

时间:2011-10-31 18:45:06

标签: c++ templates struct arrays

我正在使用我的结构模板:

#pragma pack(push, 1)
template <typename T>
struct S
{
   T t;

   inline void Set(const T& val) { t = val; }
}
#pragma pack(pop)

T可以是float,int,short或char [10],char [1]或char [2](最好是任何长度都很棒)。

虽然上面的内容似乎对整数类型的效果非常好,但我在实现char [n]部分方面遇到了困难:

  1. 我需要使用strncpy或memcpy而不是赋值运算符
  2. 使用上面的代码,编译器会抱怨签名(const char [2]&amp; val),并通过s.Set(“T”)调用它。
  3. S与完整和​​字符类型之间的接口必须与调用它们的通用代码相同(并且它不关心它们是什么类型)。

3 个答案:

答案 0 :(得分:4)

T等情况下,您可以为char[10]定义模板专精。当您这样做时,是否还有任何问题?但正如Mat已经指出的那样,使用字符串是一种值得考虑的方法。

#include <iostream>

#pragma pack(push, 1)
template <typename T>
struct S
{
   T t;

   inline void Set(const T& val) { std::cout << "general\n"; }
};

template <int len>
struct S<char[len]>
{
   char t[len];

   inline void Set(const std::string& val) { std::cout << "specialization\n"; }
};
#pragma pack(pop)

int main() {

    S<int> a;
    a.Set(10);

    S<char[20]> b;
    b.Set("turkey!");

    return 0;
}

http://codepad.org/X8YVuFja输出:

  

一般
  专业化

答案 1 :(得分:2)

嗯,部分专业化可能会起到作用:

template <typename T> struct S
{
  T x;
  void set(const T & y) { x = y; }
};

template <typename T, unsigned int N> struct S<T[N]>
{
  T x[N];
  void set(const T (&y)[N]) { std::copy(y, y + N, x); }
};

用法:

S<char[10]> b;
char c[10] = "Hello";
b.set(c);

答案 2 :(得分:0)

对我来说很好:http://codepad.org/03FSqZC6

#pragma pack(push, 1)
template <typename T>
struct S
{
   T t;

   inline void Set(const T& val) {}
};
#pragma pack(pop)

int main() {
    typedef char (carray)[10];  //do you have a line like this?
    S<carray> lhs;
    carray rhs = "HELLO";
    lhs.Set(rhs);
    return 0;
}

很可能您的问题是由使用不正确的数组类型引起的。有关正确typedef的示例,请参阅我的代码。

编辑:

我刚刚意识到,如果您已经拥有Set或任何类型的动态数组,那么调用std::string会很麻烦。做模板专业化。