Click here to Skip to main content
15,897,891 members
Articles / Programming Languages / C++

Type-safe Callbacks in C++

Rate me:
Please Sign up or sign in to vote.
4.71/5 (47 votes)
13 Feb 2008CPOL8 min read 204K   4.9K   130  
Demonstrates how to use type-safe callbacks in C++
// Test.cpp

#include "stdafx.h"
#include "Test.h"
#include "cList.h"


/*************************** Main Test *************************/

void cTest::StartDemo()
{
	printf("\n--> Inserting some words into the list:\n\n");

	// filling the list with words
	cList i_WordList;
	i_WordList.Append("This");
	i_WordList.Append("is");
	i_WordList.Append("a");
	i_WordList.Append("test");
	i_WordList.Append("!");
	
	i_WordList.Print();

	// --------------------------------------

	printf("\n\n\n--> Sorting words alphabetically:\n\n");

	// Generating a callback which takes two char* params and returns int.
	// The callback function is "SortByAlphabet()" and resides 
	// in the class "cTest" and has the instance pointer "this"
	cCallGen<cTest, int, char*, char*> i_Call_1(this, SortByAlphabet);

	// Setting the callback function for further calls to BubbleSort()
	i_WordList.SetCallback(&i_Call_1);

	i_WordList.BubbleSort();
	i_WordList.Print();

	// --------------------------------------

	printf("\n\n\n--> Sorting words by length:\n\n");

	// Generating a callback which takes two char* params and returns int.
	// The callback function is "SortByLength()" and resides 
	// in the class "cTest" and has the instance pointer "this"
	cCallGen<cTest, int, char*, char*> i_Call_2(this, SortByLength);

	// Setting the callback function for further calls to BubbleSort()
	i_WordList.SetCallback(&i_Call_2);

	i_WordList.BubbleSort();
	i_WordList.Print();

	printf("\n\n\nPress any key !");

	getchar();
	exit(0);
}


/********************************

  The callback functions have to return:
  <0 if Param1 < Param2
   0 if Param1 = Param2
  >0 if Param1 > Param2

/*******************************/


int cTest::SortByAlphabet(char* s8_Word1, char* s8_Word2)
{
	return stricmp(s8_Word1, s8_Word2);
}


int cTest::SortByLength(char* s8_Word1, char* s8_Word2)
{
	return strlen(s8_Word1) - strlen(s8_Word2);
}


By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) ElmüSoft
Chile Chile
Software Engineer since 40 years.

Comments and Discussions