English 中文(简体)
模板特化 (Móbǎn tèhuà)
原标题:Templates specialization

我有以下的模板集:

//1  
template< typename T > void funcT( T arg )  
{
    std::cout<<"1: template< typename T > void funcT( T arg )";  
}  
//2  
template< typename T > void funcT( T * arg )  
{
    std::cout<<"2: template< typename T > void funcT( T * arg )";  
}  
//3  
template<> void funcT< int >( int arg )  
{  
    std::cout<<"3: template<> void funcT< int >( int arg )";  
}  
//4  
template<> void funcT< int * >( int * arg )  
{  
    std::cout<<"4: template<> void funcT< int *>( int * arg )";  
}  

//...  

int x1 = 10;  
funcT( x1 );  
funcT( &x1 );  

Can someone please explain why funcT( x1 ); calls function #3 and funcT( &x1 ); calls function #2 but not #4 as expected?
I have already read this article http://www.gotw.ca/publications/mill17.htm which says that "overload resolution ignores specializations and operates on the base function templates only". But according to this logic funcT( x1 ); should call function #1, not #3. I am confused.

问题回答

功能#3和#4是功能#1的专业化,而不是分别是功能#1和#2的专业化。

这意味着你的编译器会优先选择#1和#2之间。当它选择#1作为funcT(x1)的最佳匹配时,然后选择专门化的#3。对于funcT(&x1),它选择#2作为最佳匹配并找不到专门化。

以 #4 为例说明

template<> void funcT<>( int * arg )

它变成了#2的专业化,您将获得预期的结果,即#4被称为funcT(&x1)。

另一个选择是简单地写下来

void funcT(int *arg)

如果常规函数匹配,就会始终选择它们而不是模板版本。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签