What is the equivalent of C ++ in common?

Suppose I implement a polymorphic tree data structure that can accept any type of data ...

Tree<Int> or Tree<String> or Tree<Object>

but I implement it in C ++ .... how would I point out that a tree can contain an arbitrary type similar to generics in Java

there is also the equivalent of a Java Object in C ++ in which all objects in C ++ inherit from Object

+5
source share
7 answers

The closest equivalent to Java generic is a template in C ++. Its equivalent as such, strictly speaking. But this is what you have in C ++. Therefore, in order to satisfy your needs, you need to work a bit so that you can write equivalent C ++ code.

, ++ Java:

+3

, , , Boost Any. , , , , .

+3

++

template <typename T>
    class Tree {
        TreeNode<T> Root
        ...
    };

, ( ). , , . ++ , .

+1

, , ++ templates.

:

template<class TType>
class AClass
{
private:
    TType *somePointer;
};

++, # Java. , , void*, , .

+1

generics: Tree<Int> Tree<String> ; . Tree<Object> "" , ++ , "". "" , Boost.Any, .

++ :

template<typename T>
class Tree {
    ...
};

:

Tree<int> treeOfInts;
+1

, java- Tree<void*>. , :

class TreeBase { };
class TreeInt : public TreeBase { int i; };

Tree<TreeBase*>. , . Java.

Tree<Node> n; struct Node { TreeBase *b; };

, ++ , ++:

class TreeNode { virtual ~TreeNode() { } };
class MyIntTreeNode : public TreeNode {
public:
    MyTreeNode(int i) : i(i) { }
    int i;
};
class MyStringTreeNode : public TreeNode {
public:
   MyStringTreeNode(string s) : s(s) { }
   string s;
};
class MyArrayTreeNode : public TreeNode {
public:
   MyArrayTreeNode(std::vector<TreeNode*> v) : v(v) { }
   std::vector<TreeNode*> v;
};

, :

int main() {
  MyIntTreeNode n1(10);
  MyStringTreeNode n2("abc");
  std::vector<TreeNode*> v;
  v.push_back(&n1);
  v.push_back(&n2);
  MyArrayTreeNode n3(v);
  algo(n3);
  }

This approach has the advantage that each treenode can have a different behavior. The disadvantage is that it is a bit detailed.

0
source

All Articles