Archive

Posts Tagged ‘type_traits’

C++ Using template type to make decision about how to extend class

June 4, 2013 Leave a comment

so the problem was a follow, I had a parent template class and as usual template child class extended from the parent class. Objective was depending upon what type of the Child class to select the type of the parent template.

Therefore went looking for how to pick up the  type of the variable depending upon the template. Found this really nice post. http://stackoverflow.com/questions/8243134/c-templates-select-different-type-based-on-value-of-template-parameter

Using information in it and little experimentation following code shows how to do it.

//============================================================================
// Name        : forTestingAndTrying.cpp
// Author      : Mohsen Ali
// Version     :
// Copyright   : use freely on your own risk, but contribute
// Description : testing template
//============================================================================
#include <iostream>
#include <type_traits>
using namespace std;

/*Parent Class*/
template<typename T>
struct parentMe{
T myData;
void print(void){
cout << "parentMe datasize " << sizeof(myData) <<endl;
}

};

template<bool B>
struct stUseless: parentMe<typename std::conditional<B, double, float>::type>{
typedef typename std::conditional<B, char, int>::type T;
typedef typename std::conditional<B, double, float>::type T2;

T dat;
void print(){
cout <<"Size is " <<  sizeof(dat) <<endl;
parentMe<T2>::print();
cout <<" --------------------  " <<  endl;
}
};

int main() {
stUseless<false> a;
a.print();

stUseless<true> b;
b.print();

cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}

and the output is below

Size is 4
parentMe datasize 4
——————–
Size is 1
parentMe datasize 8
——————–
!!!Hello World!!!

Categories: C++ Tags: , , ,