Template function specialization
Aug 18, 2015 at 4:12pm UTC
I have an header like this:
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 66 67 68
#ifndef Templates_Header_h
#define Templates_Header_h
#include <iostream>
using namespace std;
template <typename T>
struct S
{
private :
T val;
public :
S() : val{} {};
T* get();
T* get() const ;
T set();
T operator =(const T&);
T read_val(T& v);
void print_val() const ;
};
template <typename T>
void S<T>::print_val() const
{
cout << "Value is: " << val << endl;
}
template <typename T>
T* S<T>::get()
{
T* p = &val;
return p;
}
template <typename T>
T S<T>::set()
{
T newvalue;
cout << "Type new value: " ;
cin >> newvalue;
S<T>::val = newvalue;
return S<T>::val;
}
template <typename T>
T S<T>::operator =(const T&)
{
T val1;
val1 = val;
return *this ;
}
template <typename T>
T* S<T>::get() const
{
T* p = &val;
return p;
}
template <typename T>
T S<T>::read_val(T &v)
{
cout << "Type Value: " ;
cin >> v;
return S<T>::val = v;
}
#endif
And its source file:
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
#include <stdio.h>
#include "Header.h"
#include "std_lib_facilities.h"
template <>
struct S <int > // Specialization
{
private :
int val;
public :
S() : val{0} {};
int read_val(int & v);
};
template <>
struct S<char > // Specialization
{
private :
char val;
public :
S() : val{'0' } {};
};
template <>
struct S<double > // Specialization
{
private :
double val;
public :
S() : val{0.0} {};
};
template <>
struct S<string> // Specialization
{
private :
string val;
public :
S() : val{"" } {};
};
template <>
struct S<vector<int >> // Specialization
{
private :
vector<int > val;
public :
S() : val{0} {};
};
Now I wish to specialize function
T read_val(T& v)
for all types I have specialized struct S, except for
vector<int >
.
I have tried to read and to search on the web but I always do something wrong and I am not able to figure out how to do it. Could you help me please?
Thanks!
Last edited on Aug 18, 2015 at 4:13pm UTC
Aug 18, 2015 at 6:50pm UTC
I am sorry IT was bad written in my book. I apologize.
Topic archived. No new replies allowed.