Search Results

Search found 13 results on 1 pages for 'crtp'.

Page 1/1 | 1 

  • Mixins, variadic templates, and CRTP in C++

    - by Eitan
    Here's the scenario: I'd like to have a host class that can have a variable number of mixins (not too hard with variadic templates--see for example http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.103.144). However, I'd also like the mixins to be parameterized by the host class, so that they can refer to its public types (using the CRTP idiom). The problem arises when trying to mix the too--the correct syntax is unclear to me. For example, the following code fails to compile with g++ 4.4.1: template <template<class> class... Mixins> class Host : public Mixins<Host<Mixins>>... { public: template <class... Args> Host(Args&&... args) : Mixins<Host>(std::forward<Args>(args))... {} }; template <class Host> struct Mix1 {}; template <class Host> struct Mix2 {}; typedef Host<Mix1, Mix2> TopHost; TopHost *th = new TopHost(Mix1<TopHost>(), Mix2<TopHost>()); With the error: tst.cpp: In constructor ‘Host<Mixins>::Host(Args&& ...) [with Args = Mix1<Host<Mix1, Mix2> >, Mix2<Host<Mix1, Mix2> >, Mixins = Mix1, Mix2]’: tst.cpp:33: instantiated from here tst.cpp:18: error: type ‘Mix1<Host<Mix1, Mix2> >’ is not a direct base of ‘Host<Mix1, Mix2>’ tst.cpp:18: error: type ‘Mix2<Host<Mix1, Mix2> >’ is not a direct base of ‘Host<Mix1, Mix2>’ Does anyone have successful experience mixing variadic templates with CRTP?

    Read the article

  • Mixing policy-based design with CRTP in C++

    - by Eitan
    I'm attempting to write a policy-based host class (i.e., a class that inherits from its template class), with a twist, where the policy class is also templated by the host class, so that it can access its types. One example where this might be useful is where a policy (used like a mixin, really), augments the host class with a polymorphic clone() method. Here's a minimal example of what I'm trying to do: template <template <class> class P> struct Host : public P<Host<P> > { typedef P<Host<P> > Base; typedef Host* HostPtr; Host(const Base& p) : Base(p) {} }; template <class H> struct Policy { typedef typename H::HostPtr Hptr; Hptr clone() const { return Hptr(new H((Hptr)this)); } }; Policy<Host<Policy> > p; Host<Policy> h(p); int main() { return 0; } This, unfortunately, fails to compile, in what seems to me like circular type dependency: try.cpp: In instantiation of ‘Host<Policy>’: try.cpp:10: instantiated from ‘Policy<Host<Policy> >’ try.cpp:16: instantiated from here try.cpp:2: error: invalid use of incomplete type ‘struct Policy<Host<Policy> >’ try.cpp:9: error: declaration of ‘struct Policy<Host<Policy> >’ try.cpp: In constructor ‘Host<P>::Host(const P<Host<P> >&) [with P = Policy]’: try.cpp:17: instantiated from here try.cpp:5: error: type ‘Policy<Host<Policy> >’ is not a direct base of ‘Host<Policy>’ If anyone can spot an obvious mistake, or has successfuly mixing CRTP in policies, I would appreciate any help.

    Read the article

  • Templated derived class in CRTP (Curiously Recurring Template Pattern)

    - by Butterwaffle
    Hi, I have a use of the CRTP that doesn't compile with g++ 4.2.1, perhaps because the derived class is itself a template? Does anyone know why this doesn't work or, better yet, how to make it work? Sample code and the compiler error are below. Source: foo.C #include <iostream> using namespace std; template<typename X, typename D> struct foo; template<typename X> struct bar : foo<X,bar<X> > { X evaluate() { return static_cast<X>( 5.3 ); } }; template<typename X> struct baz : foo<X,baz<X> > { X evaluate() { return static_cast<X>( "elk" ); } }; template<typename X, typename D> struct foo : D { X operator() () { return static_cast<D*>(this)->evaluate(); } }; template<typename X, typename D> void print_foo( foo<X,D> xyzzx ) { cout << "Foo is " << xyzzx() << "\n"; } int main() { bar<double> br; baz<const char*> bz; print_foo( br ); print_foo( bz ); return 0; } Compiler errors foo.C: In instantiation of ‘foo<double, bar<double> >’: foo.C:8: instantiated from ‘bar<double>’ foo.C:30: instantiated from here foo.C:18: error: invalid use of incomplete type ‘struct bar<double>’ foo.C:8: error: declaration of ‘struct bar<double>’ foo.C: In instantiation of ‘foo<const char*, baz<const char*> >’: foo.C:13: instantiated from ‘baz<const char*>’ foo.C:31: instantiated from here foo.C:18: error: invalid use of incomplete type ‘struct baz<const char*>’ foo.C:13: error: declaration of ‘struct baz<const char*>’

    Read the article

  • Having trouble storing a CRTP based class in a vector

    - by user366834
    Hi, Im not sure if this can be done, im just delving into templates so perhaps my understanding is a bit wrong. I have a Platoon of soldiers, the platoon inherits from a formation to pick up the formations properties, but because i could have as many formations as i can think of I chose to use the CRTP to create the formations, hoping that i could make a vector or array of Platoon to store the platoons in. but, of course, when i make a Platoon, it wont store it in the vector, "types are unrelated" Is there any way around this ? i read about "Veneers" which are similar and that they work with arrays but i cant get it to work, perhaps im missing something. here's some code: (sorry about the formatting, the code is here in my post but its not showing up for some reason ) template < class TBase > class IFormation { public : ~IFormation(){} bool IsFull() { return m_uiMaxMembers == m_uiCurrentMemCount; } protected: unsigned int m_uiCurrentMemCount; unsigned int m_uiMaxMembers; IFormation( unsigned int _uiMaxMembers ): m_uiMaxMembers( _uiMaxMembers ), m_uiCurrentMemCount( 0 ){} // only allow use as a base class. void SetupFormation( std::vector<MySoldier*>& _soldierList ){}; // must be implemented in derived class }; ///////////////////////////////////////////////////////////////////////////////// // PHALANX FORMATION class Phalanx : public IFormation<Phalanx> { public: Phalanx( ): IFormation( 12 ), m_fDistance( 4.0f ) {} ~Phalanx(){} protected: float m_fDistance; // the distance between soldiers void SetupFormation( std::vector<MySoldier*>& _soldierList ); }; /////////////////////////////////////////////////////////////////////////////////// // COLUMN FORMATINO class Column : public IFormation< Column > { public : Column( int _numOfMembers ): IFormation( _numOfMembers ) {} ~Column(); protected: void SetupFormation( std::vector<MySoldier*>& _soldierList ); }; I then use these formations in the platoon class to derive, so that platoon gets the relevant SetupFormation() function: template < class Formation > class Platoon : public Formation { public: **** platoon code here }; everything works great and as expected up until this point. now, as my general can have multiple platoons, I need to store the platoons. typedef Platoon< IFormation<> > TPlatoon; // FAIL typedef std::vector<TPlatoon*> TPlatoons; TPlatoon m_pPlatoons m_pPlatoons.push_back( new Platoon<Phalanx> ); // FAIL, types unrelated. typedef Platoon< IFormation< TPlatoon; fails because i need to specify a template parameter, yet specifying this will only allow me to store platoons created with the same template parameter. so i then created FormationBase class FormationBase { public: virtual bool IsFull() = 0; virtual void SetupFormation( std::vector<MySoldier*>& _soldierList ) = 0; }; and made IFormation publicly inherit from that, and then changed the typedef to typedef Platoon< IFormation< FormationBase > > TPlatoon; but still no love. now in my searches i have not found info that says this is possible - or not possible.

    Read the article

  • C++ CRTP(template pattern) question

    - by aaa
    following piece of code does not compile, the problem is in T::rank not be inaccessible (I think) or uninitialized in parent template. Can you tell me exactly what the problem is? is passing rank explicitly the only way? or is there a way to query tensor class directly? Thank you #include <boost/utility/enable_if.hpp> template<class T, // size_t N, class enable = void> struct tensor_operator; // template<class T, size_t N> template<class T> struct tensor_operator<T, typename boost::enable_if_c< T::rank == 4>::type > { tensor_operator(T &tensor) : tensor_(tensor) {} T& operator()(int i,int j,int k,int l) { return tensor_.layout.element_at(i, j, k, l); } T &tensor_; }; template<size_t N, typename T = double> // struct tensor : tensor_operator<tensor<N,T>, N> { struct tensor : tensor_operator<tensor<N,T> > { static const size_t rank = N; }; I know the workaround, however am interested in mechanics of template instantiation for self-education

    Read the article

  • C++ CRTP question

    - by aaa
    following piece of code does not compile, the problem is in T::rank not be inaccessible (I think) or uninitialized in parent template. Can you tell me exactly what the problem is? is passing rank explicitly the only way? or is there a way to query tensor class directly? Thank you #include <boost/utility/enable_if.hpp> template<class T, // size_t N, class enable = void> struct tensor_operator; // template<class T, size_t N> template<class T> struct tensor_operator<T, typename boost::enable_if_c< T::rank == 4>::type > { tensor_operator(T &tensor) : tensor_(tensor) {} T& operator()(int i,int j,int k,int l) { return tensor_.layout.element_at(i, j, k, l); } T &tensor_; }; template<size_t N, typename T = double> // struct tensor : tensor_operator<tensor<N,T>, N> { struct tensor : tensor_operator<tensor<N,T> > { static const size_t rank = N; }; I know the workaround, however am interested in mechanics of template instantiation for self-education

    Read the article

  • Usage of CRTP in a call chain

    - by fhw72
    In my widget library I'd like to implement some kind of call chain to initialize a user supplied VIEW class which might(!) be derived from another class which adds some additional functionality like this: #include <iostream> template<typename VIEW> struct App { VIEW view; void init() {view.initialize(); } }; template<typename DERIVED> struct SpecializedView { void initialize() { std::cout << "SpecializedView" << std::endl; static_cast<DERIVED*>(this)->initialize(); } }; struct UserView : SpecializedView<UserView> { void initialize() {std::cout << "UserView" << std::endl; } }; int _tmain(int argc, _TCHAR* argv[]) { // Cannot be altered to: App<SpecializedView<UserView> > app; App<UserView> app; app.init(); return 0; } Is it possible to achieve some kind of call chain (if the user supplied VIEW class is derived from "SpecializedView") such that the output will be: console output: SpecializedView UserView Of course it would be easy to instantiate variable app with the type derived from but this code is hidden in the library and should not be alterable. In other words: The library code should only get the user derived type as parameter.

    Read the article

  • Java CRTP: Works for container but not for methods?

    - by Daniel
    I have a baseclass with a protected static ArrayList. I want to have a seperate ArrayList for each kind of subclass that extends this baseclass. This is when I applied CRTP: public class BaseExample<T> { protected static ArrayList<Integer> data = new ArrayList<Integer>(); } This works just fine. However, when I try to implement the following static method in the same base class, it doesn't adhere to CRTP: public static void clear() { data.clear(); } For example: class SubExample extends BaseExample<SubExample> { // insertion methods accessing 'data' field // these work fine :) } SubExample.clear(); // does not seem to clear data container Do I need to somehow explicitly specify T in my baseclass clear method? Note: These are all pure static classes.

    Read the article

  • "Inherited" types using CRTP and typedef

    - by Ken Moynihan
    The following code does not compile. I get an error message: error C2039: 'Asub' : is not a member of 'C' Can someone help me to understand this? Tried VS2008 & 2010 compiler. template <class T> class B { typedef int Asub; public: void DoSomething(typename T::Asub it) { } }; class C : public B<C> { public: typedef int Asub; }; class A { public: typedef int Asub; }; int _tmain(int argc, _TCHAR* argv[]) { C theThing; theThing.DoSomething(C::Asub()); return 0; }

    Read the article

  • How to write curiously recurring templates with more than 2 layers of inheritance?

    - by Kyle
    All the material I've read on Curiously Recurring Template Pattern seems to one layer of inheritance, ie Base and Derived : Base<Derived>. What if I want to take it one step further? #include <iostream> using std::cout; template<typename LowestDerivedClass> class A { public: LowestDerivedClass& get() { return *static_cast<LowestDerivedClass*>(this); } void print() { cout << "A\n"; } }; template<typename LowestDerivedClass> class B : public A<LowestDerivedClass> { public: void print() { cout << "B\n"; } }; class C : public B<C> { public: void print() { cout << "C\n"; } }; int main() { C c; c.get().print(); // B b; // Intentionally bad syntax, // b.get().print(); // to demonstrate what I'm trying to accomplish return 0; } How can I rewrite this code to compile without errors (and output "C\nB\n")?

    Read the article

  • Unique ID Defined by Most-Derived Class accessible through Base Class

    - by Narfanator
    Okay, so, the idea is that I have a map of "components", which inherit from componentBase, and are keyed on an ID unique to the most-derived*. Only, I can't think of a good way to get this to work. I tried it with the constructor, but that doesn't work (Maybe I did it wrong). The problem with any virtual, etc, inheritance tricks are that the user has to impliment them at the bottom, which can be forgotten and makes it less... clean. *Right phrase? If - is inheritance; foo is most-derived: foo-foo1-foo2-componentBase Here's some code showing the problem, and why CRTP can't cut it: (No, it's not legit code, but I'm trying to get my thoughts down) #include<map> class componentBase { public: virtual static char idFunction() = 0; }; template <class T> class component : public virtual componentBase { public: static char idFunction(){ return reinterpret_cast<char>(&idFunction); } }; class intermediateDerivations1 : public virtual component<intermediateDerivations1> { }; class intermediateDerivations2 : public virtual component<intermediateDerivations2> { }; class derived1 : public intermediateDerivations1 { }; class derived2 : public intermediateDerivations1 { }; //How the unique ID gets used (more or less) std::map<char, componentBase*> TheMap; template<class T> void addToMap(componentBase * c) { TheMap[T::idFunction()] = c; } template<class T> T * getFromMap() { return TheMap[T::idFunction()]; } int main() { //In each case, the key needs to be different. //For these, the CRTP should do it: getFromMap<intermediateDerivations1>(); getFromMap<intermediateDerivations2>(); //But not for these. getFromMap<derived1>(); getFromMap<derived2>(); return 0; } More or less, I need something that is always there, no matter what the user does, and has a sortable value that's unique to the most-derived class. Also, I realize this isn't the best-asked question, I'm actually having some unexpected difficultly wrapping my head around it in words, so ask questions if/when you need clarification.

    Read the article

  • How do boost operators work?

    - by FredOverflow
    boost::operators automatically defines operators like + based on manual implementations like += which is very useful. To generate those operators for T, one inherits from boost::operators<T> as shown by the boost example: class MyInt : boost::operators<MyInt> I am familiar with the CRTP pattern, but I fail to see how it works here. Specifically, I am not really inheriting any facilities since the operators aren't members. boost::operators seems to be completely empty, but I'm not very good at reading boost source code. Could anyone explain how this works in detail? Is this mechanism well-known and widely used?

    Read the article

  • Test Driven Development with C++: How to test a class which depends on other classes?

    - by Nikhil
    Suppose I have a class A which depends on 3 other classes X, Y and Z, either A uses these through a reference or a pointer or say A is templated to be instantiated with X, Y and Z doesn't matter, the key is that in order to test A, I need to have X, Y and Z. So I need to have fakes for A, B and C. Suppose I write them. Now, how do I swap real and fake objects easily? I can see that this works very easily in the case of templates. In order to make it work when A depends on X, Y and Z through a reference or a pointer, I would need to have a base class say X_Interface from which I can inherit X_Real and X_Fake. So basically, I would end up in having 3 times the number of classes for every class that would need to have a fake. I am most likely missing something. There has to be a simpler way to do this. Having a base class X_Interface is also quite expensive as I will be using more space and making virtual calls. I guess I could use CRTP as I know whether its a X_Real or X_Fake at compile time but still there must be a better way.

    Read the article

1