2013-03-28 73 views
3

我正在研究函数的模板。为了简化,说它看起来像这样: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字符串允许成为模板参数,当我读过的时候说它不能是。我一定误解/误解了有关模板的内容。

+0

可能重复:http://stackoverflow.com/questions/6973040/specialize-a-void-function-template-to-a-const-charn – 2013-03-28 04:51:09

回答

3

没有C-string类型。术语C字符串定义了内容,而不是类型。它指的是字符数组的一部分,它的某个地方有一个空字符,它被某些函数解释为意味着字符串的结尾。

你是什么人在思想上真正感兴趣的,是一个字符串文字。字符串文字的类型为const char[N],其中N是字符串中的字符数,包括隐式空终止符。所以"hello world"的类型是const char[12]。您可以专门为它是这样的:

template<> 
void f(const char(&x)[12]) 
{ 
    cout << "const char[12] case" << endl; 
    cout << x << endl; 
} 

注意,这仅覆盖大小12的阵列。然而,你可以重载,(不是专业)f()所有尺寸是这样的:

template<size_t N> 
void f(const char(&x)[N]) 
{ 
    cout << "const char[" << N << "] case" << endl; 
    cout << x << endl; 
} 

还要注意,这些方法也会覆盖正常的命名数组。没有办法区分它们和字符串文字。

0

。注意,这也将作为为const char [N]和常量字符*既会推断出,

template < typename T > 
void f(const T* x) 
{ 
    cout << "const char* case" << endl; 
    cout << x << endl; 
} 

专业化这里是恒定指针类型。

如果您需要基于char数组类型或指针类型的特化,则还可以使用简单函数重载。