Why can't T
be deduced from fn
's signature in the following example?
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;
}
Where in contrast, the following example without the operator<<
being a regular member is legal:
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;
}
Member functions of class templates (C++ only) You may define a template member function outside of its class template definition. The overloaded addition operator has been defined outside of class X . The statement a + 'z' is equivalent to a. operator+('z') .
Example: Declare member function templatesMember function templates of non-template classes or class templates are declared as function templates with their template parameters. C++ Copy. // member_function_templates.cpp struct X { template <class T> void mf(T* t) {} }; int main() { int i; X* x = new X(); x->mf(&i); }
A member function template cannot be virtual, and a member function template in a derived class cannot override a virtual member function from the base class.
A function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.
Because just like you're using Class<1>
instead of Class
, you have to provide the template parameter to the function template fn
as well:
Class<1>() << fn<1>;
Also, you might want to return a reference from your operator <<
:
template<typename T>
Class & operator <<( void (*)(const Class<I> &, const T &) ) { return *this; }
^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With