Nested Class Causing Problems with Templating - class

For my Data Structures class we've been asked to take a previously implemented balanced tree(from a prior project) and use it to implement parts of the C++ standard map class.
http://cplusplus.com/reference/stl/map/
I figured the most obvious first step was to template the entire class, allowing for separate key and storage types. Of course, I ran into problems with templating. Generally my templating works until I attempt to template a function that is using a local nested datatype "rbNode". If I include template parameters in the function definition, I get syntax errors. If I leave them out, I get "template parameters not included" errors.
This is the class implementation that gives me the errors in Visual Studio 2010 (errors listed below):
#include <cstdlib>
#include <iostream>
template <class key_type, class T>
class myMap
{
private:
//typedef pair<const key_type, T> value_type;
struct rbNode
{
//value_type ref;
int element;
rbNode * left;
rbNode * right;
bool red;
rbNode(int key)
{
left = NULL;
right = NULL;
//ref.first = key;
//ref.second = element;
element = key;
red = true;
}
};
rbNode * root;
bool search(int , rbNode *);
rbNode * LL_Rotation(rbNode *);
};
template <class key_type, class T>
myMap<key_type,T>::rbNode* myMap<key_type,T>::LL_Rotation(rbNode * curr) // errors occur on this line
{
rbNode * temp = curr->right;
curr->right = temp->left;
temp->left = curr;
curr->red = 1;
temp->red = 0;
return temp;
}
This function, however, compiles just fine with the above function commented out:
template <class key_type,class T>
bool myMap<key_type,T>::search(int key,rbNode * tree)
{
if(tree!=NULL)
if(tree->element==key)
return true;
else
if(key< tree->element)
return search(key,tree->left);
else
return search(key,tree->right);
else
return false;
}
In particular, I'm getting
missing ';' before '*'
and
missing type specifier - int assumed. Note: C++ does not support default-int
on the line the implementation for "LLRotation"'s name is in (pointed out in comment). I'm not very experienced with templating, so I get the feeling the I'm making a very stupid mistake. Regardless, if you need more of my code, or more information, let me know. Any help is greatly appreciated.
Note: I'm sure my code has plenty of bad practices, etc. in it. I'm still learning. Feel free to point them out, but I'm mostly concerned with the templating issues.

You're just missing a typename for the dependent name:
template <class key_type, class T>
typename myMap<key_type,T>::rbNode* myMap<key_type,T>::LL_Rotation(rbNode * curr)
^^^^^^^^

Related

Error naming the class

I have this code (snippet):
for (itr = GameObjectList.begin(); itr != GameObjectList.end(); ++itr)
{
if ((*itr)->GetComponent<Light>() && (*itr)->GetComponent<Light>()->GetEnable())
{
(*itr)->GetComponent<Light>()->Render();
}
}
Error in line 3 and line 5. The reason, the name "Light" which is a Component of my engine, if I change the name of the class Light to any other name (example "Light2") it works!
the GetComponent template function is:
template <typename T>
T* GetComponent()
{
for(itr = CompList.begin() ; itr != CompList.end() ; ++itr)
{
if (T* type = dynamic_cast<T*>(*itr))
{
return type;
}
}
return NULL;
};
what the f#%k is happening? maybe a file corruption, with my cpp files? i don't know
Thanks in advance!
EDIT:
error: no matching function for call to 'GameObject::GetComponent()'
I have found the error! In the GameObject class a have an enum with the type of the gameObject, one of the element was "Light" , and that enum was global. The solution is to make the enum public.

Class in parameter of function (Arduino) does not compile

I am trying to create a simple class in C++, but I keep getting the compilation errors:
main:2: error: variable or field 'doSomething' declared void
main:2: error: 'person' was not declared in this scope
main:
class person {
public:
int a;
};
void doSomething(person joe) {
return;
}
main() and stuff would go here, but even if I include main(){}, the errors still occur. I also tried adding 2 closed parentheses after joe, but then that creates the error:
main: In function 'void doSomething(person (*)())':
main:8: error: request for member 'a' in 'joe', which is of non-class type 'person (*)()'
Any help is greatly appreciated. (I hope this isn't something really stupid I'm missing, because I've been researching for hours).
Edit: I found out this is an Arduino-specific error. This post answers it.
I found out after reading this post that a way to work around this is:
typedef struct person{
public:
int a;
};
void doSomething(void *ptr)
{
person *x;
joe = (person *)ptr;
joe->a = 3; //To set a to 3
//Everything else is normal, except changing any value of person uses "->" rather than "."
return;
}
main()
{
person larry;
doSomething(&larry);
}
So essentially it is:
-Change class to typedef struct
-in the parameter, replace newtype with void *something
-add person *x; and x = (person *)ptr; to the beginning of the function
-whenever accessing type property, use -> rather than .
I'm not a expert but when I try to do what you want to do, I do it this way:
//create an instance of my class
MyAwesomeClass myObject;
void myFunction(MyAwesomeClass& object){
//do what you want here using "object"
object.doSomething();
object.doSomethingElse();
}
void setup() {
//setup stuff here
myObject.init();
}
void loop() {
//call myFunction this way
myFunction(myObject);
}
As I said, I'm not a C++ expert but it does the job.
Hope it helps!
My guess is, you have an invalid syntax error somewhere in the declarations above "class person...". Can you copy and paste the whole file?

Using boost::program_options with own template class possible?

I'm currently start using boost::program_options for parsing command line options as well as configuration files.
Is it possible to use own template classes as option arguments? That means, something like
#include <iostream>
#include "boost/program_options.hpp"
namespace po = boost::program_options;
template <typename T>
class MyClass
{
private:
T* m_data;
size_t m_size;
public:
MyClass( size_t size) : m_size(size) { m_data = new T[size]; }
~MyClass() { delete[] m_data; }
T get( size_t i ) { return m_data[i]; }
void set( size_t i, T value ) { m_data[i] = value; }
};
int main (int argc, const char * argv[])
{
po::options_description generic("General options");
generic.add_options() ("myclass", po::value< MyClass<int>(2) >(),
"Read MyClass");
return 0;
}
Trying to compile this I get an Semantic Issue (No matching function for call to 'value'). I guess I need to provide some casting to an generalized type but I have no real idea.
Can anybody help?
Thanks
Aeon512
I wouldn't know if boost::program_options allows the use-case you are trying, but the error you are getting is because your are trying to pass an object as a template type to po::value<>. If the size is known at compile-time, you could have the size be passed in as a template parameter.
template< typename T, size_t size >
class MyClass {
T m_data[size];
public:
// ...
};
And then use it like so:
po::value< MyClass<int, 2> >()
You should also look into using Boost.Array instead that I guess fulfills what you are trying to implement.
I would write it like this:
MyClass<int> mine(2);
generic.add_options() ("myclass", po::value(&mine), "Read MyClass");
Then all that needs to be done is to define an input stream operator like this:
std::istream& operator >>(std::istream& source, MyClass& target);
Then Boost Program Options will invoke this stream operator when the myclass option is used, and your object will be automatically populated according to that operator's implementation, rather than having to later call one of the Program Options functions to extract the value.
If you don't prefer the above syntax, something like should work too:
generic.add_options() ("myclass", po::value<MyClass<int> >()->default_value(MyClass<int>(2)), "Read MyClass");
This way you would be creating the instance of your class directly with your desired constructor argument outside of the template part where runtime behavior isn't allowed. I do not prefer this way because it's verbose and you end up needing to call more functions later to convert the value.

Emulating 'return' in macro

Is there any standard compliant way to emulate 'return' with macro?
Currently, I'm trying to wrapping _alloca function to emulate variable length array on stack (which is supported in C99) with macro in C++. Since the _alloca function manipulates stack pointer, I think inline function isn't suitable solution for this time.
Below is the current code that I've written.
template <typename T>
inline void __placement_new_array(T arr[], const size_t size) {
assert(size > 0);
for (size_t i = 0; i < size; i++) {
new (&arr[i]) T;
}
}
template <typename T>
class __arraydtor
{
public:
__arraydtor(T arr[], size_t size) : arr_(arr), size_(size) {}
~__arraydtor() {
for (size_t i = size_ - 1; i != (size_t)(-1); i--) {
arr_[i].~T();
}
}
private:
T* arr_;
size_t size_;
};
#define stack_alloc(size) _alloca(size)
#define stacknew(ptr, type, size) \
ptr = static_cast<type*>(stack_alloc(sizeof(type) * size));\
__placement_new_array(ptr, size);\
__arraydtor<type> __##type##_dtor_instance(ptr,size)
...
type* pos;
stacknew(pos, type, size);
I think the code is fairly usable even for now (it works for most type at least in vs2005), but ultimately I want to acheive the macro that can be used like below -
pos = stacknew(type, size);
(Of course pos = stacknew type[size]; would be more cool but I don't think there is a way to acheive it with any C++ compiler)
Since the macro contains some declaration, emulating 'return' is impossible in the current form - it might be impossible or needs a different approach. But I'm lack of experience for using macro, I can not judge whether it's possible or not.
Also I want to note that above code is not safe when the ctor of the target array throws exception - I'd also be grateful if someone suggests a way to improve the macro.
you can use , operator:
v = (expr1, expr2); // evaluate both expressions, return rightmost

Doxygen for C++ template class member specialization

When I write class templates, and need to fully-specialize members of those classes, Doxygen doesn't recognize the specialization - it documents only the generic definition, or (if there are only specializations) the last definition. Here's a simple example:
===MyClass.hpp===
#ifndef MYCLASS_HPP
#define MYCLASS_HPP
template<class T> class MyClass{
public:
static void foo();
static const int INT_CONST;
static const T TTYPE_CONST;
};
/* generic definitions */
template<class T>
void MyClass<T>::foo(){
printf("Generic foo\n");
}
template<class T>
const int MyClass<T>::INT_CONST = 5;
/* specialization declarations */
template<> void MyClass<double>::foo();
template<> const int MyClass<double>::INT_CONST;
template<> const double MyClass<double>::TTYPE_CONST;
template<> const char MyClass<char>::TTYPE_CONST;
#endif
=== MyClass.cpp ===
#include "MyClass.hpp"
/* specialization definitions */
template<>
void MyClass<double>::foo(){
printf("Specialized double foo\n");
}
template<> const int MyClass<double>::INT_CONST = 10;
template<> const double MyClass<double>::TTYPE_CONST = 3.141;
template<> const char MyClass<char>::TTYPE_CONST = 'a';
So in this case, foo() will be documented as printing "Generic foo," INT_CONST will be documented as set to 5, with no mention of the specializations, and TTYPE_CONST will be documented as set to 'a', with no mention of 3.141 and no indication that 'a' is a specialized case.
I need to be able to document the specializations - either within the documentation for MyClass<T>, or on new pages for MyClass<double>, MyClass<char>. How do I do this? Can Doxygen even handle this? Am I possibly doing something wrong in the declarations/code structure that's keeping Doxygen from understanding what I want?
I should note two related cases:
A) For templated functions, specialization works fine, e.g.:
/* functions that are global/in a namespace */
template<class T> void foo(){ printf("Generic foo\n"); }
template<> void foo<double>(){ printf("Specialized double foo\n"); }
This will document both foo<T>() and foo<double>().
B) If I redeclare the entire template, i.e. template<> class MyClass<double>{...};, then MyClass<double> will get its own documentation page, as a seperate class. But this means actually declaring an entirely new class - there is no relation between MyClass<T> and MyClass<double> if MyClass<double> itself is declared. So I'd have to redeclare the class and all its members, and repeat all the definitions of class members, specialized for MyClass<double>, all to make it appear as though they're using the same template. Very awkward, feels like a kludge solution.
Suggestions? Thanks much :)
--Ziv
Further seeking indicates that this issue was an open bug, fixed in Doxygen 1.8.10.
This bug appears to be fixed 3 weeks ago