我希望能够基于常量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]");
}
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
K-b*_*llo 13
任何chars 数组的特化是:
template< std::size_t N >
struct Test< const char[N] > { ... };
Run Code Online (Sandbox Code Playgroud)
但是,除非您编写更多元函数以将非类型模板参数转换为其文本表示,否则您将无法再返回char*from type().