我正在研究函数的模板。为了简化,说它看起来像这样:C++模板C字符串参数
template < typename T >
void f(const T & x)
{
cout << "generic case" << endl;
cout << x << endl;
}
我一直认为C字符串不能用作模板参数参数。但实际以下工作(使用G ++ 4.5.1):
f("hello world");
所以我的问题是:什么是T
当我叫f("hello world")
?
我想专门看看究竟发生了什么。例如,因为char[]
是const char*
我看着这个(这显然是行不通的):
template < typename T >
void f(const T & x)
{
cout << "generic case" << endl;
cout << x << endl;
}
template <>
void f(const const char * T & x)
{
cout << "char[] case" << endl;
cout << x << endl;
}
,并尝试了几种变化。他们都没有工作。
题外话:我并不真的需要这对我在做什么。我需要为T =“C字符串”的情况下,所以我只写了另一个模板功能的专业化:
template < typename T >
void f(const T & x)
{
cout << "generic case" << endl;
cout << x << endl;
}
template < typename T >
void f(T x[])
{
cout << "T[] case" << endl;
cout << x << endl;
}
我只是问,因为我很好奇,究竟是什么发生的事情,为什么是C字符串允许成为模板参数,当我读过的时候说它不能是。我一定误解/误解了有关模板的内容。
可能重复:http://stackoverflow.com/questions/6973040/specialize-a-void-function-template-to-a-const-charn – 2013-03-28 04:51:09