c++ - Explicit friend specialization of template function in class template -
i'm facing situation arise 2 questions how adl , template function specialization works under circumstances.
why can't use cout inside friend specialization definition? in scenario i'm getting link error stating
basic_stream
undefined, if switch callcat
compilation proceed.template<class t> void func1(t&){ ... } void cat(){ cout << "foo.func1" <<endl; } namespace first{ template<class r> struct foo{ friend void func1<>(foo<int>&){ cout << "foo.func1" <<endl; // cat(); } }; } foo<int> f; func1(f);
why adl doesn't apply when change specialization refer template class param? if i'm not wrong adl mechanic, in order resolve right version of
func1
call in 3 (e.g. global(1), or friend defined one(2)) collects possible matches , selects concrete one. and, think concrete 1 version offunc1
in 2, because instead of specifying function param dependent of template param, specify concrete typefoo
func1
in 1 doesn't, adl selectfunc1
in 1 anyway. why ?template<class t> void func1(t&){ // 1 ... } namespace first{ template<class r> struct foo{ friend void func1<>(foo<r>&){ // 2 cout << "foo.func1" <<endl; } }; } foo<int> f; func1(f); // 3
template parameters unrelated friend declarations. you'll need carry them disambiguated in thefriend
declaration:
template<class r> struct foo{ template<typename u> friend void func1<u>(foo<u>&){ cout << "foo.func1" <<endl; // cat(); } };
also case should decide, if want put friend definition inlined above, or provide declaration:
template<class r> struct foo{ template<typename u> friend void ::func1<u>(foo<u>&); };
the latter should match friend
template function in global namespace explicitly, , specialization can made necessary:
template<> void func1(int&){ // ... } template<> void func1(std::string&){ // ... } // a.s.o.
Comments
Post a Comment