CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Aug 2005
    Posts
    69

    Template and Inheritance

    I've several classes (D3, D4, etc) which I would like to pass to the constructor of class C. All of these classes (D3, D4, etc) derived from an abstract class called AbstractGroup. I'm having problem of defining the constructor of C. Here is the code:
    Code:
    #include <iostream>
    #include <string>
    #include <map>
    #include <algorithm>
    using namespace std;
    
    template<class Type>
    class AbstractGroup {
    public:
    	virtual Type	element(int) const = 0;
    	virtual int	order() const = 0;
    	virtual Type	inverse(const Type& x) const = 0;
    	virtual Type	operation(const Type& left, const Type& right) const = 0;
    };
    
    class D3 : public AbstractGroup<string> {
    //...
    };
    
    class D4 : public AbstractGroup<double> {
    //...
    };
    
    class C {
    public:
    	C(const AbstractGroup<class Type>& g) {}
    };
    
    int main()
    {
    	D3 d3;
    	C c(d3);  //Error: 'C::C(const AbstractGroup<Type> &)' : cannot convert 
                          //parameter 1 from 'D3' to 'const AbstractGroup<Type> &'
    
    	return 0;
    }
    I could write C's constructor as template. But I want to restrict the use of C to only those classes which are derived from AbstractGroup. How can I do that? Please help. Thanks for your time.
    ~Donotalo()

  2. #2
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: Template and Inheritance

    Your constructor needs to be a templated function:
    Code:
    class C {
    public:
    	template <typename Type>
    	C(const AbstractGroup<Type>& g) {}
    };
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured