C ++中的模板方法,用于将wchar_t *或char *分配给数组

时间:2014-03-04 15:11:11

标签: c++ arrays char

我有以下问题。我有一个模板方法接受一个普通数组或long char*如下:

template <class myType>
static void createArray(const myType* (&MyArray)[10])

现在,我想根据myType变量char*wchar_t为此数组指定值。我创建了一个小方法,告诉我,myType长或不长,以便我可以分配类型,如下所示:

MyArray[1] =  ( MyTemplate<myType>::isWide()) ? L"-1" : "-1";

不幸的是,我总是收到一个错误,我无法将wchar_t分配给char数组,反之亦然。 我不能使用字符串类。 任何想法,如果这是可能的? 谢谢!

1 个答案:

答案 0 :(得分:1)

问题是在编译时,存在类型不匹配的问题。这是你想要的技巧:

template <typename t>
struct x {
    static t *c;
};

template<>
char *x<char>::c = "-1";
template<>
wchar_t *x<wchar_t>::c = L"-1";