Operators, implicit conversion and templates

Discussion in 'C++' started by Christophe Poucet, Mar 25, 2005.

  1. Hello,

    I have a few questions concerning automatic conversion. Apparently I
    seem to be having an issue in that in certain cases it works and in
    certain cases not. Could anyone perhaps tell me why the 4th test case
    does not automatically convert while it shows in the 5th case that
    these types are equivalent.
    Basically the ddt template is to simulate a pointer or an array and
    the var template is just a wrapper I use.

    With regards,
    Christophe Poucet

    ---------------------- CODE --------------------------
    #include <cstdio>
    using namespace std;
    template <typename T>
    class var {
    public:
    var() {}

    var(T data) : data_(data) {}

    template <typename T2>
    var(T2 data) : data_(data) {}

    operator const T&() const { return data_; }

    template <typename T2> var & operator= (const T2& data) { data_ =
    data; }

    private:
    T data_;
    };

    template <typename T>
    class ddt{
    public:
    ddt(T* ptr) : ptr_(ptr) {}

    T& operator[](const size_t n) { return ptr_[n]; }

    const T& operator[](const size_t n) const { return ptr_[n]; }

    ddt & operator=(T* ptr) { ptr_ = ptr; }
    private:
    T* ptr_;
    };

    int main() {
    {
    var<int>* x = new var<int>[1];
    x[0] = 1; // works
    }
    {
    ddt<var<int> > x = new var<int>[1];
    x[0] = 1; // Works
    }
    {
    var<var<int>*> x = new var<int>[1];
    x[0] = 1; // Works
    }
    {
    var<ddt<var<int> > > x = new var<int>[1];
    x[0] = 1; // Does not work
    }
    {
    var<ddt<var<int> > > x = new var<int>[1];
    static_cast<ddt<var<int> > >(x)[0] = 1; // Works
    }
    return 0;
    }

    // g++ -O3 -o templatetest templatetest.cpp
    // templatetest.cpp: In function `int main()':
    // templatetest.cpp:50: no match for `var<ddt<var<int> > >& [int]'
    operator
    // make: *** [templatetest] Error 1
    Christophe Poucet, Mar 25, 2005
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. JKop
    Replies:
    3
    Views:
    454
  2. Generic Usenet Account
    Replies:
    3
    Views:
    800
    Generic Usenet Account
    Jul 14, 2005
  3. recover
    Replies:
    2
    Views:
    789
    recover
    Jul 25, 2006
  4. Replies:
    2
    Views:
    310
    A.W. van den Heuvel
    Dec 13, 2007
  5. moorep312

    implicit char conversion in templates

    moorep312, Nov 11, 2010, in forum: C Programming
    Replies:
    0
    Views:
    284
    moorep312
    Nov 11, 2010
Loading...

Share This Page