gcc 4.7.3 涓嶆敮鎸佹垚鍛樺嚱鏁版ā鏉跨壒鍖栥傚涓嬩唬鐮侊細
#ifndef __MEMFUNTEMPLATE_H__
#define __MEMFUNTEMPLATE_H__
#include <stdio.h>
class Base {};
class Derived :
public Base {};
struct Functor {
template <typename T>
void function() {
printf(" Primary template

.\n");
}
template<>
void function<
int>(){
printf(" Specialization for int

.\n");
}
template<>
void function<Base *>() {
printf(" Specialization for Base *

.\n");
}
};
class Tester {
public:
static void DoTest()
{
Functor functor;
functor.function<
char>();
functor.function<
int>();
functor.function<Base *>();
functor.function<Derived *>();
}
};
#endif // __MEMFUNTEMPLATE_H__鍦?VS2010 涓紪璇戣繍琛屾槸娌℃湁闂鐨勶紝浣嗗湪 gcc 4.7.3涓嬶紝緙栬瘧閮介氫笉榪囷細
../src/MemFunTemplate.h:21:14: error: <strong>explicit specialization in non-namespace scope</strong> ‘struct Functor’
../src/MemFunTemplate.h:22:24: error: template-id ‘function<int>’ in declaration of primary template
../src/MemFunTemplate.h:26:14: error: explicit specialization in non-namespace scope ‘struct Functor’
../src/MemFunTemplate.h:26:38: error: template-id ‘function<Base*>’ in declaration of primary template
../src/MemFunTemplate.h:26:21: error: ‘void Functor::function()’ cannot be overloaded
../src/MemFunTemplate.h:22:10: error: with ‘void Functor::function()’
../src/MemFunTemplate.cpp: In function ‘int main()’:
../src/MemFunTemplate.cpp:17:2: error: ‘DoTest’ is not a member of ‘Functor’
涓轟簡杈懼埌榪戜技鎴愬憳鍑芥暟妯℃澘鐗瑰寲鐨勬晥鏋滐紝鍙互鍒╃敤鎴愬憳鍑芥暟涓繪ā鏉夸互鍙婇噸杞藉嚱鏁版潵瀹炵幇錛?br />
/*
* MemFunTemplate.h
*
* Created on: Jul 12, 2013
* Author: http://blog.csdn.net/kesalin/
*/
#ifndef MEMFUNTEMPLATE_H_
#define MEMFUNTEMPLATE_H_
#include <stdio.h>
template<typename T>
struct DummyIdentity {
typedef T type;
};
class Base {};
class Derived : public Base {};
struct Functor {
template <typename T> void function() {
function(DummyIdentity<T>());
}
private:
template <typename T>
void function(DummyIdentity<T>) {
printf(" Primary template DummyIdentity<T>

.\n");
}
void function(DummyIdentity<int>) {
printf(" overload function for DummyIdentity<int>

.\n");
}
void function(DummyIdentity<Base *>) {
printf(" overload function for DummyIdentity<Base *>

.\n");
}
};
class Tester {
public:
static void DoTest()
{
Functor functor;
functor.function<char>();
functor.function<int>();
functor.function<Base *>();
functor.function<Derived *>();
}
};
#endif /* MEMFUNTEMPLATE_H_ */
璋冪敤 DoTest() 榪愯緇撴灉濡備笅錛?/p>
Primary template DummyIdentity<T>

.
overload function
for DummyIdentity<
int>

.
overload function
for DummyIdentity<Base *>

.
Primary template DummyIdentity<T>

.
娉ㄦ剰錛?/span>
VS2010 鐗堟湰鐨勪唬鐮侊紝妯℃澘褰㈠弬涓?T錛屽湪瀹炰緥鍖栦笉浼氳繘琛岄殣寮忕被鍨嬭漿鎹€傚嵆鐢?nbsp;Derived * 褰撲綔瀹炲弬璋冪敤鐨勬槸涓繪ā鏉匡紝鑰屼笉鏄?Base * 鐗瑰寲鐗堟湰
鑰屽湪 gcc 涓嬶紝妯℃澘褰㈠弬铏界劧涔熶負T錛屼絾褰卞搷閲嶈澆鍐寵鐨?function 鍙傛暟涓猴細DummyIdentity<T>錛岀敤涓嶅悓鐨勫疄闄呭弬鏁板疄渚嬪寲璇ユā鏉匡紝寰楀埌鐨勬槸涓鍫嗛噸杞藉嚱鏁般傚洜姝ょ敤 Derived * 褰撲綔瀹炲弬鏃訛紝璋冪敤鐨勫嚱鏁拌嚜鐒跺氨鏄疄渚嬪寲鐨?nbsp;void function(DummyIdentity<T>)浜嗐?/p>