Is it good to have a member template function inside a class without a template in C ++?

I wonder if there is good practice to have a member function inside a class without a template in C ++? Why?

I'm trying to do something like this

in classA.h: classA { public: member_func1(); member_func2(); }; in classA.cpp: template <class T> share_func(); classA::member_func1() { call share_func(); } classA::member_func2() { call share_func(); } 

I wonder if this fits?

+4
source share
5 answers

This is absolutely legal use of template functions. In addition, there is no problem using the template member functions of a class other than the template. For instance:

 class A { public: void say_hello() { cout << "Hello World" << endl; } template<T> print_it( T arg ) { cout << "Argument: " << arg << endl; } }; ... A a; a.say_hello(); a.print_it( 3.14159 ); a.print_it( "A string" ); 
+7
source

If a member function logically belongs to your class, and the type of the template is specific only to this function (and has nothing to do with the rest of your class), I see no reason not to do this.

+4
source

Function templating is an easy way to overload it with different types of arguments, which is quite acceptable. In this sense, it is even acceptable for a template to have one member function in a class without a template or to call a template function from a class other than a template. There is nothing ambiguous about this.

+1
source

If you have many methods that have similar signatures, only changing in type, the template method is the way to go:

 struct Example { void load_from(std::istream&); void load_from(Database_Table&); void load_from(Some_Device&); }; 

The template method allows some extension:

 struct Example_Template_Method { template <class Input_Source> void load_from(Input_Source&); }; 

The key point here is that template allows you to use a method, function or algorithm to work with various types of objects without changing the algorithm. This can also apply to interfaces.

+1
source

Yes, that’s good, of course, as usual, you should better factor as much as possible from the template.

For instance:

 class Tokens { public: void add(const char* c); void add(const std::string& s); template <class T> void add(T const& t) { this->add(boost::lexical_cast<std::string>(t)); } private: std::vector<std::string> mTokens; }; 

This makes boredom conversions from the user's circle easier.

+1
source

Source: https://habr.com/ru/post/1305789/


All Articles