Where / how to define a template

What is the best score for defining a template in C ++?

template <class T>
class A
{
private:
    // stuff
public:
    T DoMagic()
    {
        //method body
    }
}

Or:

template <class T>
class A
{
private:
    // stuff
public:
    T DoMagic();
}

template <class T>
A::T DoMagic()
{
    // magic
}

Another way? I seem to stumble over some debate on this. So; Which way to choose?

+3
source share
6 answers

This is completely a matter of style. However, it said:

  • choose a method and stick to it - either all built-in, or all, or mixed based on some rule
  • I personally use the 3 line rule. If the body of the method in the template is longer than 3 lines, I move it outside.

inline ( POV), , .

+4

, , , . , , .

, , CPP, . , .

file.cpp

template<class Gizmo> bool DoSomethingFancy()
{
 // ...
}

, , H:

utility.h

template<class Gizmo> bool DoSomethingUseful() 
{
  // ...
}

, , . , :

utility.h

template<class Type> class Useful
{
  bool FunctionA();
  bool FunctionB();
};

template<class Type> bool Useful<Type>::FunctionA()
{
  // ...
}

template<class Type> bool Useful<Type>::FunctionB()
{
  // ...
}

. , INC . #include INC :

utility.h:

template<class Type> class MoreUseful
    {
      bool FunctionA();
      bool FunctionB();
    };

#include "utility.inc"

utility.inc:

template<class Type> bool MoreUseful<Type>::FunctionA()
{
  // ...
}

template<class Type> bool MoreUseful<Type>::FunctionB()
{
  // ...
}
+2

() . , .

, . , template , .

, , .

+1

, , , ++ - " ":

template <class T>
struct A
{
     T foo();
     T bar(T * t);
     T baz(T const & t);
};

template <class T>  // Made-up syntax
{
    T A::foo()
    {
        //...
    }

    T A::bar(T * t)
    {
        //...        
    }

    T A::baz(T const & t)
    {
        //...
    }
}
+1

(.. ), . , , , , .

+1

, , .

, ? . , , . , .

0

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


All Articles