c++ - How to pass in template type parameter -



c++ - How to pass in template type parameter -

i having give-and-take co-worker templates, , 1 of things talking given class such following, how away having switch statement via usage of templates?

enum eversion { version_1, version_2, }; class cbar { ... public: eversion ver; }; class cfoo { void reset() { switch (pbar->ver) { case version_1: templatehelpermethod<version_1>::dosomething(); break; case version_2: templatehelpermethod<version_2>::dosomething(); break; } } cbar *pbar; }; cfoo* pfoo = new cfoo(pbar); pfoo->reset();

one solution create derived templated class, , move function derived class needs utilize switch statement based on version.

class cfoo { ... cbar *pbar; }; template <eversion ver> class cfoo2 : public foo { void reset() { templatehelpermethod<ver>::dosomething(); } }; cfoo2<version_2>* pfoo = new cfoo2<version_2>(pbar); pfoo->reset();

however, co-worker suggested it's possible maintain original function in base of operations class, , alter templated method (something below). however, little dense on how work. how utilize derived class pass type templated method now? if has ideas, please allow me know. thanks.

class cfoo { template <eversion ver> void reset() { templatehelpermethod<ver>::dosomething(); } cbar *pbar; }; template <eversion ver> class cfoo2 : public foo { // go here? }; cfoo2<version_2>* pfoo = new cfoo2<version_2>(pbar); pfoo->reset(); or cfoo* pfoo = new cfoo(pbar); // can this? since cfoo2 derives cfoo // , has no additional members... cfoo2<version_2>* pfoo2 = static_cast<cfoo2<version_2>*>(pfoo); pfoo2->reset();

i think co-worker suggested not possible since pbar->ver not compile time constant. cannot utilize template parameter.

the right solution remove switch on runtime variable runtime polymorphism

struct version { virtual ~version() = default; virtual void dosomething() = 0; }; class cbar { public: version& ver; }; class cfoo { public: void reset() { pbar->ver.dosomething(); } cbar *pbar; };

if create cbar::ver compile time constant can utilize specialize cfoo on it.

template<eversion version> struct cbar { eversion version = version; }; template<eversion version> struct cfoo { void reset(); cbar<version> pbar; }; template<> void cfoo<version_1>::reset() { } template<> void cfoo<version_2>::reset() { }

c++ templates

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -