我想与一个功能模板交朋友,并希望尽可能限制模板类型。朋友模板功能,避免虚拟功能/抽象基地
下面是一个较大的层次结构的片段,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