Help with explicit instantiation

E

E. Robert Tisdale

cat X.h
#ifndef GUARD_X_H
#define GUARD_X_H 1
#include <iostream>

template<class T>
class X {
private:
// representation
T D;
public:
// functions
T data(void) const { return D; }
// constructors
X(T d = 0): D(d) { }
X(const X& x);
template<class S>
X(const X<S>& x);
friend
std::eek:stream& operator<<(
std::eek:stream& os, const X<T>& x) {
return os << x.data();
}
};

#endif//GUARD_X_H 1
#include "X.h"

template<class T>
X<T>::X(const X& x): D(x.D) {
std::cerr << "copy constructor" << std::endl;
}

template<class T>
template<class S>
X<T>::X(const X<S>& x): D(x.data()) {
std::cerr << "conversion constructor" << std::endl;
}

template X<float>::X(const X<int>& x);
template X said:
g++ -Wall -ansi -pedantic -c X.cc
X.cc:15: error: ambiguous template specialization `X<>' \
for `X<float>::X(const X<float>&)'
X.cc:4: error: candidates are: \
X<T>::X(const X<T>&) [with T = float]
X.h:17: error: \
template<class S> X::X(const X<S>&) [with S = S, T = float]

What did I do wrong?
 
E

E. Robert Tisdale

Sumit said:
Seems to compile without errors/warnings on Comeau C++ 4.3.3 and MSVC++ 7.1.

I just tried it with my SGI MIPSpro C++ compiler
and it compiles without complaint there as well.

I guess that it's a GNU C++ compiler bug.

Can anybody suggest a work-around?
 
Y

Yevgen Muntyan

Hi,
it seems to be very old bug - look at
http://gcc.gnu.org/ml/gcc-prs/2000-q3/msg00288.html

To workaround it maybe try to use extra parameter: X<T>(X<S>, int).
The following code compiles well with gcc-3.4.

Yevgen


/////////////////////////////////////////////////
// X.h

#ifndef GUARD_X_H
#define GUARD_X_H 1
#include <iostream>

template<class T>
class X {
private:
// representation
T D;
public:
// functions
T data(void) const { return D; }
// constructors
X(T d = 0): D(d) { }
X(const X& x);
template<class S>
X(const X<S>& x, int i = 0);
friend
std::eek:stream& operator<<(std::eek:stream& os, const X<T>& x) {
return os << x.data();
}
};

#endif//GUARD_X_H 1

///////////////////////////////////////////
// X.cc

#include "X.h"

template<class T>
X<T>::X(const X& x): D(x.D)
{
std::cerr << "copy constructor" << std::endl;
}

template<class T>
template<class S>
X<T>::X(const X<S>& x, int i): D(x.data())
{
std::cerr << "conversion constructor" << std::endl;
}


template X<float>::X(const X<int>& x, int);
template X<float>::X(const X<float>& x);

void f()
{
X<float> a(X<float>(1.0));
X<float> b(X<int>(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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top