Seite 1 von 1

[C++] Template und Copy-c'tor Spezialisierung

Verfasst: 24.01.2013, 13:37
von Matthias Gubisch
Hallo zusammen

ich habe hier eine Templateklasse vorliegen, etwa so in der art

Code: Alles auswählen

template<class T>
class foo_t
{
public:
foo_t(T a, T b, T c);
foo_t(const foo_t<T>& other) //copy c'tor

fpp_t<T>& operator=(const fooD_t<T>& other);
protected:
private:
  T a, b, c;
};
Was ich jezt machen möchte ist folgendes:

Code: Alles auswählen

foo_t<float> f (1, 2, 3);
foo_t<double> d(f);

oder:
d = f;

Das ganze soll nur für festgelegte Typkombinationen festglegt sein.
Mein Problem ist jezt wie muss die Spezialisierung von Copykonstruktor und Assingmentoperator aussehen in dem Fall?

Meine intuitiven Ansätze endeten alle mit unterschiedlichen Kompilerfehlermeldungen :(

Vielleicht kann mir einer der ganzen C++ spezialisten hier einen Tipp geben.

Re: [C++] Template und Copy-c'tor Spezialisierung

Verfasst: 24.01.2013, 13:51
von Krishty
Rein aus dem Kopf:

    template <typename OtherT> foo_t(OtherT const & other); // copy c'tor

und als Spezialisierung für double:

    template <typename T> template <> foo_t<T>::foo_t<double>(double const & other) { …

Probier das mal.

Re: [C++] Template und Copy-c'tor Spezialisierung

Verfasst: 24.01.2013, 14:03
von B.G.Michi

Code: Alles auswählen

#include "stdio.h"

template<class T>
class foo_t
{
   template<class> friend class foo_t;
   
public:
   foo_t(T _a, T _b, T _c) : a(_a), b(_b), c(_c) {}
   foo_t(const foo_t<T>& _other) : a(_other.a), b(_other.b), c(_other.c) {}

   template<class T2>
   foo_t(const foo_t<T2>& _other);

private:
     T a, b, c;
};

template<> template<>
foo_t<double>::foo_t(const foo_t<float>& _other)
   : a(_other.a), b(_other.b), c(_other.c)
{
   printf("foo_t<double>::foo_t(const foo_t<float>&)");
}

int main(void)
{
   foo_t<float> f(1, 2, 3);
   foo_t<double> d(f);
}
Funktioniert unter GCC 4.7.2 und clang++ 3.2. Bin aber nicht ganz sicher ob die Spezialisierung von Klasse und Methode standardkonform ist.
(Edit: jetzt stimmts :) )

Re: [C++] Template und Copy-c'tor Spezialisierung

Verfasst: 24.01.2013, 14:25
von Matthias Gubisch
Danke für die Hilfe :)

Michis Version funktioniert :)

Funktioniert auch mit VS2008 falls es noch jemand interessiert