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

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

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;
cout <<" --------------------  " <<  endl;

int main() {
stUseless<false> a;

stUseless<true> b;

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: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: