【发布时间】:2011-11-01 00:18:22
【问题描述】:
我希望能够基于恒定的 c 样式字符串进行专业化。问题是当我调用我的模板化函数时,类型是 const char[N] 其中“N”是字符串 +1(空字符)的大小。我怎样才能专注于所有 c 风格的字符串?
以下代码显示了问题。您可以看到 const char [15] 的特化与“const char [15]”匹配,但对于“const char[5]”,它转到 Generic。
有没有办法做到这一点?
template <typename T>
struct Test {
static const char* type() { return "Generic"; }
};
template <>
struct Test<const char*> {
static const char* type() { return "const char*"; }
};
template <>
struct Test<const char[]> {
static const char* type() { return "const char[]"; }
};
template <>
struct Test<const char[15]> {
static const char* type() { return "const char[15]"; }
};
template <>
struct Test<char*> {
static const char* type() { return "char*"; }
};
template <>
struct Test<char[]> {
static const char* type() { return "char[]"; }
};
template <typename T>
void PrintType(const T& expected) {
std::cerr << expected << " type " << Test<T>::type() << std::endl;
}
int main(int argc, char* argv[]) {
const char* tmp = "const char*";
PrintType(tmp);
PrintType("const char[]");
PrintType("const char[15]");
PrintType("const char[5]");
}
在 Windows 7 - VS 2008 中运行时的输出
const char* type const char*
const char[] type Generic
const char[15] type const char[15]
const char[5] type Generic
【问题讨论】: