Posts

Showing posts with the label templates

C++ convert string to typename

C++ convert string to typename So I've found a variety of articles and posts saying that there is no way to convert typename to string but I haven't found one about the opposite. I have a template of a function with specializations: typename string template template <typename T> void foo(T sth) {} template <> void foo<int>(int sth) {} ... and I'm reading from a file constructed like this: int 20 double 12.492 string word Is there a way to call the correct specialization of foo() depending on the content of the file? foo() Templates are compile-time constructs, you cannot instantiate or choose template specializations at runtime – UnholySheep Jul 1 at 21:11 if (std::compare(sType)=="string" {...} else if (std::compare(sType)=="int") {......

Unable to access base class method in derived class

Unable to access base class method in derived class I have a base class as follows : class template<typename aGamePieceBase> class GamePiece : public aGamePieceBase { public: // Each GamePiece contains a definition of the base class from which it was derived typedef aGamePieceBase gamePieceBase // Returns this piece's sprite virtual sf::Sprite* getSprite() { return m_pSprite; } protected: sf::Sprite* m_pSprite; } And a derived class : class class Horse : public GameBoard::GamePiece< GameBoard::GamePieceBase > { public: virtual sf::Sprite* getSprite() override { // Do stuff } }; However I am presented with this error on the deceleration of Horse::getSprite Member function declared with override does not override a base class member Horse::getSprite Why is getSprite unavailable in Horse? getSprite GamePieceBase is as follows : GamePieceBase class GamePieceBase : public GameEventHandler { public: // Called wh...

When using templates to support functor as arguments, what qualifier should I use?

When using templates to support functor as arguments, what qualifier should I use? Consider this code: template<class F> void foo1(F f) { f(); } template<class F> void foo2(F const& f) { f(); } template<class F> void foo3(F&& f) { f(); } Which version of foo should I use? foo1 is what I see most "in the wild" but I fear that it might introduce copies that I don't want. I have a custom functor that is kind of heavy to copy so I would like to avoid that. Currently I'm leaning towards foo3 (as foo2 would disallow mutating functors) but I'm unsure about the implications. foo foo1 foo3 foo2 I'm targeting C++11. foo3 receive a forwarding reference but does not forward. The body should be std::forward<F>(f)() . I'd still suggest foo1 though. – Guillaume Racicot Jul 1 at 14:44 ...