[問題] 關於函式讀取

看板C_and_CPP作者 (Jun)時間13年前 (2010/11/18 14:25), 編輯推噓2(204)
留言6則, 3人參與, 最新討論串1/1
#include<iostream> using namespace std; namespace n1 { template <class Any> void swap(Any &a,Any &b); template <class Any> void swap(Any *a,Any *b); } int main() { int a=10,b=20; n1::swap(a,b); cout<<"a="<<a<<"\t"<<"b="<<b<<"\t"; system("pause"); } template <class Any> void n1::swap(Any &a,Any &b) { int temp; temp=a; a=b; b=temp; } template <class Any> void n1::swap(Any *a,Any *b) { int temp; temp=*a; *a=*b; *b=temp; } 我設了一個namespace n1,裡面有倆個多型n1::swap(Any &a,Any &b)跟 n1::swap(Any *a,Any *b),但是當我要使用swap的時候,swap(a,b) 它到底是會去讀n1::swap(Any &a,Any &b),還是void n1::swap(Any *a,Any *b)呢? 順道問一下我自己命名個namespace n1不知道有沒有哪裡有問題,或是語法錯誤! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 219.70.223.16

11/18 16:38, , 1F
namespace 與 template 混用?!
11/18 16:38, 1F

11/18 18:13, , 2F
第一個問題我已經解決了,是我自己觀念問題,
11/18 18:13, 2F

11/18 18:13, , 3F
想問第二個,template不能這樣用namespace?
11/18 18:13, 3F

11/18 19:26, , 4F
當然可以,不是已經有std::swap這個例子了嗎
11/18 19:26, 4F

11/18 19:31, , 5F
而第一個問題,兩個都不是,因為這是function template
11/18 19:31, 5F

11/18 19:32, , 6F
這例子是呼叫compiler生成的n1::swap(int &a,int &b)
11/18 19:32, 6F
文章代碼(AID): #1CvCRSQM (C_and_CPP)