Operators, implicit conversion and templates

C

Christophe Poucet

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top