1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| #include <iostream>
#include <memory> // std::auto_ptr<>
#include <boost/type_traits.hpp>
// Le truc qui contient les éléments et ses deux spécialisations.
template <bool is_pointer>
struct holder_type {};
template <>
struct holder_type<false> {
template <typename T>
struct type {
typedef T element_type;
typedef T holded_type;
type( element_type v ) : value_(v) {}
element_type get() const { return value_; }
private:
holded_type value_;
};
};
template <>
struct holder_type<true> {
template <typename T>
struct type {
typedef T element_type;
typedef std::auto_ptr<typename boost::remove_pointer<T>::type> holded_type;
type( element_type v ) : value_(v) {}
element_type get() const { return value_.get(); }
private:
holded_type value_;
type(type const &); // interdit à cause de std::auto_ptr<>
type & operator=(type const &); // interdit à cause de std::auto_ptr<>
};
};
// Le truc qui les contient
template <typename T>
class TrucTemplate
{
typedef typename holder_type<boost::is_pointer<T>::value>::type<T> holder;
holder holder_;
public:
TrucTemplate(const T & t) : holder_(t) {};
T const value() const { return holder_.get();}
};
template <typename T>
std::ostream & operator<<(std::ostream & os, const TrucTemplate<T> & tt)
{
return os << tt .value();
}
void test_TT() {
std::cout << "\n----------------\n";
TrucTemplate<int> tti ( 10 );
std::cout << tti << std::endl;
TrucTemplate<int *> ttpi ( new int(10) );
std::cout << ttpi << std::endl;
} |