我想與一個功能模板交朋友,並希望儘可能限制模板類型。朋友模板功能,避免虛擬功能/抽象基地
下面是一個較大的層次結構的片段,T
的template <class T> void Play(T&);
可以是T
或T<U>
的形式。如果是T<U>
,這意味着T是一個班級模板,我想與T<U>
專門的功能交朋友。
以下片段的預期行爲是成功編譯/鏈接/執行,而不產生輸出This should not be printed
。
#include <iostream>
enum class Genre { Rock = 111, Pop = 999 };
/* this is the global interface: */
template <class T> void Play(T&);
template <Genre genre> class Song {
/* befriend own player */
template <class T> friend void Play(Song<genre>&);
private:
int v = int(genre);
};
/* desired function resolution: */
template <Genre genre> void Play(Song<genre>& d)
{
std::cout << "Genre: " << d.v << std::endl;
}
template <class T> void Play(T& d)
{
std::cout << "This should not be printed" << std::endl;
}
/* these two functions are not desired but I tried... */
template<> inline void Play(Song<Genre::Pop>& d)
{ Play<Genre::Pop>(d); }
template<> inline void Play(Song<Genre::Rock>& d)
{ Play<Genre::Rock>(d); }
int main(int argc, char *argv[]) {
Song<Genre::Pop> s;
Song<Genre::Rock> p;
Play<decltype(s)>(s);
Play(s);
Play(p);
return 0;
}
爲什麼你讓你的'Play'函數專業化遞歸?你的初衷是什麼? – Abhijit
絕對不是你所謂的遞歸是我試圖調用所需的函數。 – perreal
你真的需要'玩(s);'表達式來稱呼類型超負荷? –
TartanLlama