Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deducing template member function in class template

Tags:

c++

templates

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;
}
like image 717
Kamajii Avatar asked Feb 05 '18 17:02

Kamajii


People also ask

How would you define member function outside the class template?

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') .

What is member function template explain with example?

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); }

Can a class member function template be virtual in C++?

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.

How do you call a function in a template?

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.


1 Answers

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; }
      ^
like image 51
O'Neil Avatar answered Oct 10 '22 20:10

O'Neil