What are templates in C++ 2 [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hello everybody could anyone explain to me the difference between class temlplate member functio return type of type T (parameterized type) and an object of the claas return type
template<class T>
class array
{
public:
array(T tx): tObj(tx){}
T getObj()const{return tObj;}
array GETTOBJ()const;
private:
T tObj;
}
I have confusion: what is the difference between the return value of the functions getObj() and the GETTOBJ()?????

You've got:
an array
which holds tObj
The tObj's real value is given through the arrays' constructor, and the array remembers it.
The getObj method returns the tObj, the thing that array remembered.
The GETOBJ method returns an array. It's code is not shown, but the difference is already here: it returns some array, not the thing the array remembers.
It's a difference like "returns a candy from a box" and "return the box".
Btw. I think that your sig is missing type parameter. I mean:
not: array GETTOBJ()const;
but: array<T> GETTOBJ()const;
because array is a template, and array without type parameters is meaningless.

In the folowing example "class T" is not defined so, then when initializing this class, you can add as parameters what ever you what. For example:
array <int> _array_var(); //OR
array <char> _array_var(); // OR WHAT TYPE YOU WHANT, EVEN SOME STRUCTURES OR CLASSES
in your example "T tOBJ()" will return something of the type you initialized. For example:
if you
array <int> _array_var(); // THAN T=int.... SO T tOBJ will return int type, equivalent to
int tOBJ();
and so on... class T = typename T
for more info check:
http://en.wikipedia.org/wiki/Template_(C%2B%2B)
ow yeah... and GETTOBJ returnes type of the class... always...
the can be equal GETTOBJ with tOBJ in case you define:
array <array> _array_var();

Related

Why can't I access the object using the arrow operator [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Suppose I have
struct B
{
template<typename T>
void doSomething(T& bar);
};
class A
{
//... (ctor etc.)
template<typename T>
void foo(const std::string& name, T& bar)
{
for(auto& data : myData)
{
if(data.first == name)
*(data.second)->doSomething(bar); //ERROR
}
}
private:
std::vector<std::pair<std::string, B**>> myData;
};
I thought this would work because we are iterating over 'myData' by reference, i.e. no copies, and then we do *(data.second) to access a pointer to B, which we then use the '> operator to access its 'oSomething Method.
Instead, I am just getting the error:
member reference base type 'B' is not a structure or union*
which makes no sense to me since B* is a pointer to a struct, and using the '->' operator on that would dereference the pointer revealing the actual class.
GodBolt Reproduction: https://godbolt.org/z/c45oMT
And the error mentioned in the question is because *(data.second)->doSomething(bar) is really the same as *(data.second->doSomething(bar)).
That is you try to call data.second->doSomething(bar) which is not possible because data.second is a pointer to a pointer to an object.
Then you attempt to dereference whatever doSomething returns, which also isn't possible since it doesn't return anything.
What you probably want is something like
(*data.second)->doSomething(bar);
This will first dereference data.second removing one indirection, resulting in a pointer to B (i.e. *data.second results in a B*). Then call the function on that object.

Implicit array passing/creation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I realize this is probably impossible but I will ask any ways.
Suppose I have a class:
class A{
int* array;
public:
//To be clear this class has other members
constexpr int GetSize() { return 10; /*actually this could be a little more than this*/ }
A(int arr[GetSize()]) : array(arr) { }
};
I should declare it like this:
int array[A::GetSize()] = { 0 };
A var(array);
But I am lazy and want it to be treated as if i did not declare the array at all...like this:
A var;
Is there any way to accomplish this?
Some constraints:
No dynamic memory allocation (this is for a micro controller)
I do not know the actual size of the array until I compile
The magic array number is derived from the sizeof(A) so I cannot include an array in the class because the sizeof(A) cannot be determined until after the array size is determined (which needs to know the sizeof(A))
The A class has to be able to be put into templates and initialized that way (this is the main constraint) example:
template <class T>
class Other{
public:
T foo(){
T a;
return a;
}
};
//Later
Other<A> other;
other.foo(); //This must compile
It sounds a lot like you want (at least an equivalent of) something like:
using A = std::array<int, size>;
A var;
This definitely fits your first two constraints. I can't quite figure out what your third constraint is intended to mean. You can certainly put a object of type array into a template, but it's not clear what you're talking about when you say: "and initialized that way". This can be initialized like a normal array, so A var = {0}; will be fine, if that's what you mean.
Note that although std::array was added in C++11, a reasonable analog of it can be written using only C++98 features (e.g., TR1 includes an array type that's essentially similar and compatible with C++98/03 compilers).
class B
{
friend class A;
int a, b, c; //Whatever you want here
};
class A : public B
{
int array[(sizeof B)];
public:
static constexpr int length = (sizeof B) + (sizeof int) * (sizeof B);
};

What is `using`, and what is the colon after the constructor in C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Could you help me to understand the code below? I have an interface and need to write a code. But it first time when I work with OOP. I would be grateful if you answer some questions about this code.
template <class T, class Compare = std::less<T>>
class List_of_objects {
public:
using IndexChange =
std::function<void(const T& element, size_t new_element_index)>;
explicit Heap(
Compare compare = Compare(),
IndexChange index_change = IndexChange());
// Other methods not important in my question
private:
IndexChange index_change_;
Compare compare_;
}
// Realization of methods
template<class T, class Compare>
List_of_objects<T, Compare>::List_of_objects(Compare compare, IndexChange index_change)
: compare_(compare), index_change_(index_change) {}
I have learned what std::function<> do from this site but I don't understand why we are writing using before 'IndexChange'
Also I have no idea what does compare_(compare) means, and what mean single colon in realization of List_of_objects()
I think that it is not difficult questions but I meet a deadline, I can't find answers in Stroustrup and in i-net:(
Thank you for any help!
using IndexChange = std::function<void(const T& element, size_t new_element_index)>;
permits you not to write the definition another time. This is a shortcut.
Then
IndexChange index_change_;
is the same as defining
std::function<void(const T& element, size_t new_element_index)> index_change_;
See : What is the logic behind the "using" keyword in C++?
Concerning compare_, it is the attribute where its type is defined by the template argument Compare in your definition, and by default it is std::less.
So calling compare_() will call an instance of std::less or another class if you instantiate List_of_objects with another template argument. As for example : List_of_objects<int, MyComparator> then the class MyComparator will be used instead of std::less.
See : Default template arguments for function templates
The part with the semicolons will initialize the members of your class.
See : In this specific case, is there a difference between using a member initializer list and assigning values in a constructor?
using IndexChange =
std::function<void(const T& element, size_t new_element_index)>;
You can understand this as an abbreviation for a type. Instead of having to write std::function<..... you can simply use IndexChange, as it is done here:
explicit Heap(
Compare compare = Compare(),
IndexChange index_change = IndexChange());
This is a constructor for List_of_objects:
List_of_objects<T, Compare>::List_of_objects(Compare compare, IndexChange index_change)
: compare_(compare), index_change_(index_change) {}
the part after the single colon initializes members with the parameters passed to the constructor.

Creating a function which returns a class type [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to create a function which has the type of a class Node and takes in a Node as a parameter.
Currently I have this, which isn't working;
Node return_node (Node inNode)
{
return inNode.print_values();
}
I've declared some Nodes above this, but can't work out how to utilise this function, I'm also not sure you can even make a function which takes the type as a class?
I want to be able to make a function which takes the type of a class I have declared.
The print_values() function looks like this;
void print_values()
{
cout << "A: " << A << "\nB: " << B;
}
return_node() as of right now is a function that returns a value of class Node. Judging from what you're trying to do, you're trying to print out Node's values which could have integers, strings, etc. Whether print_values() is just printing out a string or returning a string, it doesn't fit the requirements of function. To clarify, return_node() needs to return something of the Node class.
If you're just trying to print out the values (print_values prints values through cout or printf), I would suggest making return_node of type void. However, if you're trying to do return a node, try putting return inNode. You'll see that there won't be an error when you try to compile it.
EDIT: just saw the edit you made. Does the print_values() method belong to the Node class?
A class is simply a type, so the statement "a function which has the type of a class" doesn't really make sense. Rather you should just say "has type class".
You should think of functions in terms of the types they take as parameters (the function domain), and the returned type (the codomain). e.g. the function int mul2(int x) { return 2 * x; } has domain int and codomain int (i.e. int -> int).
You have declared the function return_node to have domain Node and codomain Node (i.e. Node -> Node). So does your definition (i.e. implementation) of return_node satisfy this declaration? Well, return_node simply returns the value returned by print_values which itself has implicit domain Node and codomain void. Are the codomains of return_node and print_values the same? Well no, as Node != void, therefore your definition of return_node does not satisfy the given declaration.
It is rather difficult to help you, because you are using the right terms in the wrong way. Lets start with the header:
"Creating a function which returns a class type"
No. You want to write a function that returns a value of class type.
Further...
"I'm trying to create a function which has the type of a class Node and takes in a Node as a parameter."
No. I guess what you mean is what you already said in the title: Return a Node and pass a Node as parameter (The type of your function is Node TYPE_OF_YOUR_FUNCTION (Node), just for the record).
After clarifying this, I actually do not know what your question is. If you have a class like this:
struct MyClass {
int x;
}
You can write a function for example like this:
MyClass MyMyClassFunction(MyClass a){
a.x ++;
return a;
}
In your function you arent returning anything. You declared it as returning a Node but you actually return the value of inNode.print_values(); which is void (because this is the return type of print_values()). Change it to e.g.
Node return_node (Node inNode) {
inNode.print_values();
return inNode;
}

request for member “…” in “…” which is of non-class type “…” [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my c++ program I have my own custom map composed of custom Nodes in which I am trying to obtain the "first" and "second" values (like std::map). I tried many different syntax's but to no avail.
I know the usual fix for this problem is replacing (*key_Iterator).first with (*key_Iterator)->first but in this case I need to be able to access the values in the first method.
I added the variables in the iterator class but the program did not recognize them.
template <class T, class P>
class Iterator {
public:
Node<T,P>* operator*() { return ptr_; }
private:
Node<T,P>* ptr_;
T first;
P second;
}
Any advice on how to properly implement the first version and removing this error would be greatly appreciated.
(Moving from comment)
The solution is to return a reference from your operator *, like so:
Node<T,P> &operator *() { return *ptr_; }