0

I have class:

template <class T> class Graph;

And I have a function:
template <class T>
void Graph<T>::erase_greater(T needle)
{
 if(TEMPLATE TYPE IS "STRING" OR "CHAR")
  { 
     do nothing;
  } else
  {
     if(TEMPLATE TYPE IS ONE OF THE INT TYPES)
    {
      if(strlen(var1) > strlen(var2))
      {
        USE Var2;       
       } else
        {
           USE Var1;
    }
  }
....
}

-----------
2nd question:

I have a struct:

struct graph2D {
 int id;
 bool matrix[50][50];
}

But I want to initalize the size of matrix only in main():

struct graph2D(int size) {
  int id;
  bool j[size][size];
};
int main()
{
graph2D(tmpvector.size()) MyMatrix;
}

But as I understand, this one don't work.

Thanks for any help.

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by twomers
0

You can do what's called 'template specialisation' which will implement certain functions for a specific type, basically.

template<typename ty> 
class myClass {
private:
  ty var;

public:
  myClass( ty i );
  void print( void );
};

template<typename ty>
myClass<ty>::myClass( ty i ) 
: var(i) {
}

template<>
void myClass<char>::print() {
  std::cout<< "Printint char: " << var << "\n";
}
template<>
void myClass<int>::print() {
  std::cout<< "Printing int: " << var << "\n";
}
template<typename ty>
void myClass<ty>::print() {
  std::cout<< "Printing ty: " << var << "\n";
}


int main( void ) {
  myClass<char> mych(42);
  myClass<int>  myint(43);
  myClass<double> mydoub(44);

  mych.print();
  myint.print();
  mydoub.print();

  return 0;
}

You could always use templates again for the second solution...

template<int graphSize>
struct graph2d {
  int id;
  bool j[graphSize][graphSize];
};

int main( void ) {
  std::cout<< sizeof(graph2d<12>) << "\n";
  std::cout<< sizeof(graph2d<52>) << "\n";

  return 0;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.