简体   繁体   中英

How to specify the same templated member function for multiple class types in c++?

In an effort to avoid a lot of typing, I would like to define a function once for multiple classes. My hope is that the template system would provide the definition to each of them. I suppose a non-trivial macro could accomplish this also, but they seems to be much less preferred. I do not wish to use inheritance where I could create a base class for S1,S2, due to its complications.

struct S1 {
    bool print(int i);
};

struct S2 {
    bool print(int i);
};

// bool S1::print(int i) { i=+1; std::cout<<i; return true; } NOTE: this is the line I don't want to type many times for each S*

template< typename T >
bool  T::print(int i) { i=+1; std::cout<<i; return true; }  // TODO

int main() {
S1 s1 {};
s1.print( 5 );
}

You can't use a template to "inject" a free function to become a member function of each of a number of independent classes. Sorry, just not how things work.

If you wanted to badly enough, you could do this with inheritance:

#include <iostream>

struct Base {
public:
    bool print() { 
        std::cout << "Printing something\n"; 
        return true; 
   }
};

struct S1 : Base { };

struct S2 : Base { };

int main() {
    S1 s1;
    s1.print();

    S2 s2;
    s2.print();
}

But note: inheritance brings a whole host of issues of its own, so it's open to question whether you actually want to do this or not.

What about something like this?

struct function
{
 bool print(int i);
}

struct s1: public function
{
}

Now you will be able to use the print function from s1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM