Virtual & Template method


I have the same implementation for 2 methods, they both insert argument to a text file.

1
2
3
4
5
6
7
8
9
10
11
12
void WriteToFile( double content) //for double
{
    streamFile << content;
    streamFile << flush;
}

void WriteToFile( int content) //for integer
{
    streamFile << content;
    streamFile << flush;
}  

The implementation is same, therefore I merge them to a template method:

1
2
3
4
5
6
7
template < class T>
void WriteToFile(T content)
{
    streamFile << content;
    streamFile << flush;
}  


But the WriteToFile() method should be virtual.
How can I deal with it?
http://stackoverflow.com/questions/2354210/can-a-member-function-template-be-virtual

Reconsider your design. (We cannot, because you didn't tell us enough details.)
Any trick???
Why should the WriteToFile be virtual? What does the inheritance add?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct A ; struct B ; struct C ; struct D ;

struct base
{
    virtual ~base() = default ;

    virtual void write_to_file( const A& a ) { write_to_file_impl(a) ; }
    virtual void write_to_file( const B& b ) { write_to_file_impl(b) ; }
    virtual void write_to_file( const C& c ) { write_to_file_impl(c) ; }
    virtual void write_to_file( const D& d ) { write_to_file_impl(d) ; }

    private :
        template < typename T > void write_to_file_impl( const T& )
        { /* base class has the same implementation for A, B, C, D */  }
};
One can do the other way too:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class base {
  virtual void write_impl() {
    cout << "base";
  }
public:
  virtual ~base() = default;

  template <typename T>
    void write( const T & c ) {
      write_impl();
      cout << ": " << c << " :";
      write_impl();
      cout << '\n';
    }
};

The base dictates the overall logic of the write() family, but allows customization of specific steps via virtual(s).
Topic archived. No new replies allowed.