7

I need to split one class (.h file)

#ifndef _L_H
#define _L_H
template<class L> class Myclass{
public:
  L();
  firstoperator(..);
  secondoperator(..);
private:
 ...
}
template <class L> Myclass<L>::L() ...
template <class L> Myclass<L>::firstoperator(..) ...
template <class L> Myclass<L>::secondoperator(..) ...

in two different .h file in the following form:

#ifndef _L_H
#define _L_H
template<class L> class Myclass{
public:
  L();
  firstoperator(..);
private:
 ...
}
template <class L> Myclass<L>::L() ...
template <class L> Myclass<L>::firstoperator(..) ...

#ifndef _L_H
#define _L_H
template<class L> class Myclass{
public:
  secondoperator(..);
}

template <class L> Myclass<L>::secondoperator(..) ...

how can I do it correctly without conflict?

Thank you in advance.

amo
  • 4,082
  • 5
  • 28
  • 42
Ordi
  • 73
  • 1
  • 3

3 Answers3

16

You can technically do it, but it's ugly. Don't do it.

Class1.hpp:

class MyClass
{
    int something;
    int somethingElse;

Class2.hpp:

    int somethingBig;
    int somethingSmall;
};

I hope it's clear how disgusting that is :)

tenfour
  • 36,141
  • 15
  • 83
  • 142
5

"how can I do it correctly without conflict?"

You can't. It's not possible in c++ to spread a class declaration over several header files (unlike as with c#). The declarations of all class members must appear within the class declaration body, at a single point seen in each translation unit that uses the class.

You can separate template specializations or implementation to separate header's though.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
5

You can use heritage to split class to two headers.

You can declare half class on the base and the other half on the derived.

like this:

class C12{
public:
  void f1();
  void f2();
};

can be splitted to C1 and C12

class C1{
public:
  void f1();
};

class C12: public C1{
public:
  void f2();
};

now C12 is the same as before but splitted to 2 files.

SHR
  • 7,940
  • 9
  • 38
  • 57
  • This may have unwanted side effects. If so, mentioning/recommending [mixins](http://stackoverflow.com/questions/7085265/what-is-c-mixin-style) would have been a better choice. – πάντα ῥεῖ Sep 23 '14 at 17:49
  • @πάνταῥεῖ That SO question you linked says mixins in C++ are through inheritance (unless I misread it), so I don't see how this answer is different from mentioning mixins? – MicroVirus Sep 23 '14 at 22:13
  • 1
    @MicroVirus The [`template`](http://stackoverflow.com/questions/7085265/what-is-c-mixin-style/7087257#7087257) actually makes a big difference! – πάντα ῥεῖ Sep 23 '14 at 22:17