I'm relatively new to C++ and have previously only programmed in Java. Now I want to switch and write a few programs in C++ for exercise.
In doing so, I came across a problem that I couldn't solve even after a long search: I want to create a vector with a fixed object. This object already exists and needs a template data type for creation, for example a string or an int.
Now comes the problem: I want to create objects of this data type with a method, pass the template to the method and then add the whole thing to a vector. The whole thing always returns the following error:
Error: invalid use of incomplete type
To make the problem more understandable for you, I wrote my plan in Java: You can find the files here:
Main.java:
public class Main {
public static void main(String[] args) {
TestObjectManagement testObjectManagement = new TestObjectManagement();
testObjectManagement.add(new TestObject<String>("test", "test"));
testObjectManagement.add(new TestObject<Integer>(4, "test"));
for(int i = 0; i<testObjectManagement.testarraylist.size();i++) {
System.out.println("For the name " + testObjectManagement.testarraylist.get(i).getName() + " is the value " + testObjectManagement.testarraylist.get(i).getContentType() + " saved!");
}
}
}
TestObjectManagement.java
import java.util.ArrayList;
public class TestObjectManagement {
public ArrayList<TestObject<?>> testarraylist;
public TestObjectManagement() {
testarraylist = new ArrayList<TestObject<?>>();
}
public void add(TestObject<?> testobject) {
testarraylist.add(testobject);
}
}
TestObject.java
public class TestObject<ContentType> {
String name;
ContentType t;
public TestObject(ContentType t, String name) {
this.t = t;
this.name = name;
}
public String getName() {
return name;
}
public ContentType getContentType() {
return t;
}
}
If something is unclear, please ask, but I think the source code should be easy to understand.
Many thanks for the help. Here is my C++ code: Main.cpp
#include <iostream>
#include "TestObjectManagement.h"
int main()
{
TestObjectManagement* test = new TestObjectManagement();
test->addTestObject(TestObject<int>(3));
}
TestObjectManagement.h
#pragma once
#include <iostream>
#include <vector>
#include "TestObject.h"
class TestObjectManagement
{
public:
TestObjectManagement();
void addTestObject(TestObject<class T>);
private:
std::vector<TestObject<class T>>* testVector;
};
TestObjectManagement.cpp
#include "TestObjectManagement.h"
TestObjectManagement::TestObjectManagement()
{
testVector = new std::vector<TestObject<class T>>;
}
void TestObjectManagement::addTestObject(TestObject<class T> testObeject)
{
testVector->push_back(testObeject);
}
TestObject.h
#pragma once
template <class T>
class TestObject
{
public:
TestObject(T value);
private:
T value;
};
template<class T>
TestObject<T>::TestObject(T value)
{
TestObject<T>::value = value;
}