Trying to compile a .h file without understanding something - c++

I'm trying to compile Opengazer (Open source gaze tracker) code with visual studio on windows, while the code was originally written for linux and should be compile with cmake.
Anyway, I can't compile few files.
The code won't compile is this:
Containers.h:
#pragma once
#define xforeachactive(iter,container) \
for(typeof(container.begin()) iter = container.begin(); \
iter != container.end(); iter++) \
if ((*iter)->parent == this)
template <class ParentType, class ChildType> class Container;
template <class ParentType, class ChildType>
class Containee {
protected:
void detach() { parent = 0; }
public:
ParentType *parent; /* set to null to request removal */
Containee(): parent(0) {}
virtual ~Containee() {}
};
template <class ParentType, class ChildType>
class Container {
typedef ChildType *ChildPtr;
static bool isFinished(const ChildPtr &object) {
return !(object && object->parent);
}
protected:
std::vector<ChildPtr> objects;
void removeFinished() {
objects.erase(remove_if(objects.begin(), objects.end(), isFinished),
objects.end());
}
public:
void clear() {
xforeachactive(iter, objects)
(*iter)->parent = 0;
removeFinished();
}
static void addchild(ParentType *parent, const ChildPtr &child) {
parent->objects.push_back(child);
child->parent = parent;
parent->removeFinished();
}
virtual ~Container() {
clear();
}
};
template <class ParentPtr, class ChildPtr>
class ProcessContainer: public Container<ParentPtr, ChildPtr> {
public:
virtual void process() {
xforeachactive(iter, this->objects)
(*iter)->process();
this->removeFinished();
}
virtual ~ProcessContainer() {};
};
btw Containers.cpp is empty
ad the code uses the above class is:
#pragma once
class FrameProcessing;
class FrameFunction:
public Containee<FrameProcessing, FrameFunction>
{
const int &frameno;
int startframe;
protected:
int getFrame() { return frameno - startframe; }
public:
FrameFunction(const int &frameno): frameno(frameno), startframe(frameno) {}
virtual void process()=0;
virtual ~FrameFunction();
};
class FrameProcessing:
public ProcessContainer<FrameProcessing,FrameFunction> {};
class MovingTarget: public FrameFunction {
WindowPointer *pointer;
public:
MovingTarget(const int &frameno,
const vector<Point>& points,
WindowPointer *&pointer,
int dwelltime=20);
virtual ~MovingTarget();
virtual void process();
protected:
vector<Point> points;
const int dwelltime;
int getPointNo();
int getPointFrame();
bool active();
};
class CalibrationHandler
{
public:
CalibrationHandler(void);
~CalibrationHandler(void);
};
the error I get is :
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2146: syntax error : missing ';' before identifier 'iter'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2146: syntax error : missing ')' before identifier 'iter'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2059: syntax error : ';'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2059: syntax error : ')'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2143: syntax error : missing ';' before 'if'
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(58) : error C2227: left of '->parent' must point to class/struct/union/generic type
type is ''unknown-type''
visual studio 2008\projects\eyemouse\eyemouse\containers.h(59) : error C2065: 'iter' : undeclared identifier
visual studio 2008\projects\eyemouse\eyemouse\containers.h(59) : error C2227: left of '->process' must point to class/struct/union/generic type
type is ''unknown-type''
I understand why I'm getting an error.
'iter' is not defined anywhere. anyway, this isnt my code and it should work.
I tried to copy and past the define part to the function, but still get the same error.
I'm stuck with this and trying to solve it for hours, but can't understand what to do to make it work.
I'll really be grateful for any help.

typeof is a gcc extension and equivalent to C++0x decltype there is no VS version that actually supports it.
You would need to use C++0x and decltype or try to use Boost.TypeOf, which comes with its own caveats.
Change the macro to this:
#include <boost/typeof/typeof.hpp>
#define xforeachactive(iter,container) \
for(BOOST_TYPEOF(container.begin()) iter = container.begin(); \
iter != container.end(); iter++) \
if ((*iter)->parent == this)
You could also use BOOST_AUTO if you think this is clearer.

Related

Assigning integer values from variadic template list to static const std::array member

Consider the following code snippet:
template<unsigned... IDs>
class MyClass{
public:
static const std::array<unsigned, sizeof...(IDs)> ids { IDs... };
PinIDs() = default;
};
Then use the class as:
MyClass<1,5,7,9> myClass;
The Objective would be to have ids with a size of 4, and contain the values: (1,5,7,9) respectively.
Is this type object possible or would I have to remove the static qualifier? If not how would one write this with the static qualifier. The object needs to be default constructible.
EDIT:
I tried Apple Apple's first solution and with MS Visual Studio 2017 CE on Win7
I got this compiler error:
1>------ Build started: Project: PracticeMath, Configuration: Debug Win32 ------
1>stdafx.cpp
1>PracticeMath.cpp
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(33): error C2988: unrecognizable template declaration/definition
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(33): error C2143: syntax error: missing ';' before '<'
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(33): error C2059: syntax error: '<'
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(33): error C2039: 'ids': is not a member of '`global namespace''
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(33): error C2143: syntax error: missing ';' before '{'
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(33): error C2447: '{': missing function header (old-style formal list?)
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(38): error C2065: 'myId': undeclared identifier
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(39): error C2065: 'myId': undeclared identifier
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(40): error C2065: 'myId': undeclared identifier
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(44): error C2065: 'c': undeclared identifier
1>Done building project "PracticeMath.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
With full original source like this:
#include <iostream>
#include <array>
template<unsigned... IDs>
class PinIDs{
public:
static const std::array<unsigned, sizeof...(IDs)> ids;
PinIDs() = default;
const unsigned& operator[]( unsigned idx ) const {
return ids[idx];
}
};
template<unsigned... IDs>
const std::array<unsigned, sizeof...(IDs)> PinIDs<IDs...>::ids { IDs... };
int main() {
PinIDs<4, 17, 19> myId;
std::cout << myId[0] << " ";
std::cout << myId[1] << " ";
std::cout << myId[2] << " ";
std::cout << "\nPress any key and enter to quit." << std::endl;
char c;
std::cin >> c;
return 0;
}
Thanks to StoryTeller bringing up the fact that when I tried to apply Apple Apple's 1st method I accidently mixed up MyClass as opposed to the actual name of the class in my solution - project. Once I corrected that it does compile, build and run as expected.
you can try this
#include <array>
template<unsigned... IDs>
class MyClass{
public:
static const std::array<unsigned, sizeof...(IDs)> ids;
MyClass() = default;
};
template<unsigned... IDs>
const std::array<unsigned, sizeof...(IDs)> MyClass<IDs...>::ids {IDs...};
int main(){
MyClass<1,5,7,9> myClass;
return myClass.ids[0];
}
or use constexpr/inline (both need c++17)
#include <array>
template<unsigned... IDs>
class MyClass{
public:
//static constexpr std::array<unsigned, sizeof...(IDs)> ids{IDs...};//or this
static inline const std::array<unsigned, sizeof...(IDs)> ids{IDs...};
MyClass() = default;
};
int main(){
MyClass<1,5,7,9> myClass;
return myClass.ids[0];
}
Refer to #apple apple's answer for the basics. I'll just add the C++17 way to do it. Which is quite close to your original attempt. Just add an inline specifier to the variable:
template<unsigned... IDs>
class MyClass{
public:
static inline const std::array<unsigned, sizeof...(IDs)> ids{ { IDs... } };
MyClass() = default;
};
Now the declaration can double as a definition. Oh, and mind the braces. std::array needs to be initialized as an aggregate. So one pair of {} for the std::array, and one for the internal raw array it holds.
why don't you just try it with online compiler, supporting c++17?
template<unsigned... IDs>
class MyClass{
public:
static constexpr std::array<unsigned, sizeof...(IDs)> ids { IDs... };
MyClass() = default;
};
works fine. You don't need static const inline for variables, which are computed at compile time, just use static constexpr

Game Engine SFML in C++ Errors

This is a Game Engine for SFML builded in c++. I get some errors that i don't know how to fix it. If someone can solve this problem i will apriciated a lot.
I'm still learning c so por someone could same an obious problem or solucion but i just copied the code from another page and I do exactly the same and mine code isn't working
Errors:
Error C2065: 'StateSystem' : undeclared identifier
Error C2923: 'std::unique_ptr' : 'StateSystem' is not a valid template type
argument for parameter '_Ty'
Error C3203: 'unique_ptr' : unspecialized class template can't be used as a
template argument for template parameter '_Ty', expected a real type
Error C2512: 'std::unique_ptr' : no appropriate default constructor
available
Error C2780: '_OutTy *std::move(_InIt,_InIt,_OutTy (&)[_OutSize])' : expects
3 arguments - 1 provided
1> c:\program files (x86)\microsoft visual studio
12.0\vc\include\xutility(2510) : see declaration of 'std::move'
Error C2893: Failed to specialize function template
'remove_reference<_Ty>::type &&std::move(_Ty &&) throw()'
1> With the following template arguments:
1> '_Ty=Victor::StateRef &'
Error C2227: left of '->Resume' must point to class/struct/union/generic
type
1> type is 'int'
Error C2780: '_OutTy *std::move(_InIt,_InIt,_OutTy (&)[_OutSize])' : expects
3 arguments - 1 provided
1> c:\program files (x86)\microsoft visual studio
12.0\vc\include\xutility(2510) : see declaration of 'std::move'
Error C2893:
Failed to specialize function template 'remove_reference<_Ty>::type
&&std::move(_Ty &&) throw()'
1> With the following template arguments:
1> '_Ty=Victor::StateRef &'
Error C2227: left of '->Initialize' must point to class/struct/union/generic
type
1> type is 'int'
Error C2440: 'return' : cannot convert from 'int' to 'Victor::StateRef &'
And This is the code that provides errors.
State.h
#pragma once
class State
{
public:
virtual void Initialize() = 0;
virtual void HandleInput() = 0;
virtual void Update() = 0;
virtual void Draw(float DeltaTime) = 0;
virtual void Pause()
{
}
virtual void Resume()
{
}
};
StateSystem.h
#pragma once
#include <memory>
#include <stack>
#include "State.h"
typedef std::unique_ptr <StateSystem> StateRef;
class StateSystem
{
public:
StateSystem()
{
}
~StateSystem()
{
}
void AddState(StateRef newStat, bool isReplacing = true);
void RemoveState();
void ProcessStateChanges();
StateRef &GetActiveState();
private:
std::stack<StateRef> _states;
StateRef _newState;
bool _isRemoving;
bool _isAdding;
bool _isReplacing;
};
StateSystem.cpp
#include "StateSystem.h"
void StateSystem::AddState(StateRef newState, bool isRepalcing)
{
this->_isAdding = true;
this->_isReplacing = isRepalcing;
this->_newState = std::move(newState);
}
void StateSystem::RemoveState()
{
this->_isRemoving = true;
}
void StateSystem::ProcessStateChanges()
{
if (this->_isRemoving && !this->_states.empty())
{
this->_states.pop();
if (!this->_states.empty())
{
this->_states.top()->Resume();
}
this->_isRemoving = false;
}
if (this->_isAdding)
{
if (!this->_states.empty())
{
if (this->_isReplacing)
{
this->_states.pop();
}
else
{
this->_states.top()->Pause();
}
}
this->_states.push(std::move(this->_newState));
this->_states.top()->Initialize();
this->_isAdding = false;
}
}
StateRef &StateSystem::GetActiveState()
{
return this->_states.top();
}
there's no StateSystem before typedef std::unique_ptr <StateSystem> StateRef; just add class StateSystem before it.
it says it cannot find the StateSystem class. you have to declare it first like this:
class StateSystem;
typedef std::unique_ptr <StateSystem> StateRef;
class StateSystem
{
//members
};
or put your typedef after the StateSystem definition like this:
class StateSystem
{
//members
};
typedef std::unique_ptr <StateSystem> StateRef;

Very Confused on Template INL File

Okay, I thought I had implementation files for template classes figured out, but apparently not... I have the following files in a VS 2013 C++ solution:
Main.cpp
#include "StateManager.h"
#include "State.h"
enum class Derp {
Herp,
Lerp,
Sherp,
};
int main() {
Game2D::State<Derp>::Context context(5);
Game2D::StateManager<Derp> mgr(context);
return 0;
}
StateManager.h
#pragma once
#include "State.h"
namespace Game2D {
template<typename Id>
class StateManager {
private:
typename State<Id>::Context _context;
public:
explicit StateManager(typename State<Id>::Context context);
};
#include "StateManager.inl"
}
StateManager.inl
template<typename Id>
StateManager<Id>::StateManager(typename State<Id>::Context context) :
_context(context)
{ }
State.h
#pragma once
namespace Game2D {
template<typename Id>
class StateManager;
template<typename Id>
class State {
public:
struct Context {
Context(int);
int data;
};
private:
StateManager<Id>* _manager;
Context _context;
public:
State(StateManager<Id>&, Context);
virtual ~State();
};
#include "State.inl"
}
State.inl
template<typename Id>
State<Id>::Context::Context(int data) {
this->data = data;
}
template<typename Id>
State<Id>::State(StateManager<Id>& manager, Context context) :
_manager(&manager),
_context(context)
{ }
template<typename Id>
State<Id>::~State() { }
Building this Project yields the following errors:
Error 10 error C1903: unable to recover from previous error(s); stopping compilation state.inl 9 1
Error 9 error C2065: 'context' : undeclared identifier state.inl 8 1
Error 7 error C2065: 'manager' : undeclared identifier state.inl 7 1
Error 8 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int state.inl 7 1
Error 6 error C2039: 'State' : is not a member of '`global namespace'' state.inl 6 1
Error 1 error C2143: syntax error : missing ';' before '<' state.inl 2 1
Error 2 error C2988: unrecognizable template declaration/definition state.inl 2 1
Error 3 error C2059: syntax error : '<' state.inl 2 1
Error 4 error C3083: 'Context': the symbol to the left of a '::' must be a type state.inl 2 1
Error 5 error C2039: 'Context' : is not a member of '`global namespace'' state.inl 2 1
Any help on how to fix these errors would be much appreciated!
A wild guess would be that you added your .inl files to you your project as standalone translation units and the compiler attempted to compile them as standalone translation units.
These files make no sense as standalone translation units and they will not compile as such. These are include files (aka header files). They are supposed to be seen as header files by the project. They are not supposed to be compiled directly.

symbol cannot be used in a using-declaration

I've got a header in which my base problem is with the using keyword.
#ifndef SHAPEFACTORY_H__
#define SHAPEFACTORY_H__
#include <istream>
#include <map>
#include <string>
#include "shape.h"
/* thrown when a shape cannot be read from a stream */
template<class T>
class WrongFormatException { };
template<class T>
class ShapeFactory
{
public:
using createShapeFunction=Shape<T>*()(void);
static void registerFunction(const std::string &, const createShapeFunction *);
static Shape<T> *createShape(const std::string &);
static Shape<T> *createShape(std::istream &);
private:
std::map<std::string, createShapeFunction *> creationFunctions;
ShapeFactory();
static ShapeFactory<T> *getShapeFactory();
};
#endif
And I've got some errors which I can't resolve.
1>shapefactory.h(21): error C2873: 'createShapeFunction' : symbol cannot be used in a using-declaration
1>shapefactory.h(29) : see reference to class template instantiation 'ShapeFactory<T>' being compiled
1>shapefactory.h(21): error C2143: syntax error : missing ';' before '='
1>shapefactory.h(21): error C2238: unexpected token(s) preceding ';'
1>shapefactory.h(22): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>shapefactory.h(22): error C2143: syntax error : missing ',' before '*'
1>shapefactory.h(26): error C2065: 'createShapeFunction' : undeclared identifier
1>shapefactory.h(26): error C2059: syntax error : '>'
1>shapefactory.h(29): error C2143: syntax error : missing ';' before '}'
1>shapefactory.h(29): fatal error C1004: unexpected end-of-file found
Any idea would be great.
It seems that the compiler does not support the alias decladation. Substitute it for a typedef declaration. For example (at least the code is compiled)
#include <map>
#include <string>
template <typename T>
class Shape;
template<class T>
class ShapeFactory
{
public:
typedef Shape<T>* createShapeFunction(void);
static void registerFunction(const std::string &, const createShapeFunction *);
static Shape<T> *createShape(const std::string &);
static Shape<T> *createShape(std::istream &);
private:
std::map<std::string, createShapeFunction *> creationFunctions;
ShapeFactory();
static ShapeFactory<T> *getShapeFactory();
};
int main()
{
return 0;
}

C++ Error in program compiling

Why is this c++ program giving me errors:
#include <iostream>
using namespace std;
int main (){
NumbersClass num;
num.setNumbers(1);
}
class NumbersClass
{
public:
NumbersClass() {}
void setNumbers(int i) { }
};
Here are my errors:
taskbcplus.cpp(7): error C2065: 'NumbersClass' : undeclared identifier
taskbcplus.cpp(7): error C2146: syntax error : missing ';' before identifier 'num'
taskbcplus.cpp(7): error C2065: 'num' : undeclared identifier
taskbcplus.cpp(9): error C2065: 'num' : undeclared identifier
taskbcplus.cpp(9): error C2228: left of '.setNumbers' must have class/struct/union
1> type is ''unknown-type''
You need to put the NumberClass definition before the point at which you first instantiate it, i.e. before main.
class NumbersClass
{
public:
NumbersClass() {}
void setNumbers(int i) { }
};
int main (){
NumbersClass num;
num.setNumbers(1);
}