为什么不能T
从fn
推导出来下例中的签名?
template<int I>
struct Class {
template<typename T>
Class &operator <<( void (*)(const Class<I> &, const T &) ) { return *this; }
};
struct Ot { };
template<int I>
void fn(const Class<I> &, const Ot &) { }
int main() {
Class<1>() << fn;
}
相比之下,下面的例子没有operator<<
成为正式成员(member)是合法的:
template<int I>
struct Class {
Class &operator <<( void (*)(const Class<I> &) ) { return *this; }
};
struct Ot { };
template<int I>
void fn(const Class<I> &) { }
int main() {
Class<1>() << fn;
}
最佳答案
因为就像你在使用 Class<1>
而不是 Class
,您必须向函数模板提供模板参数 fn
还有:
Class<1>() << fn<1>;
此外,您可能希望从 operator <<
返回一个引用:
template<typename T>
Class & operator <<( void (*)(const Class<I> &, const T &) ) { return *this; }
^
关于c++ - 在类模板中推导模板成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48628300/