CodingHero
CodingHero

Reputation: 3015

How do I define a generic/templated class like the C# example below

In C#:

public sealed class StateMachine<TState, TTrigger>

I'd like to write a C++ equivalent.

Upvotes: 1

Views: 126

Answers (3)

Sergey Kucher
Sergey Kucher

Reputation: 4180

You could use what Stuart and Xeo proposed, and if you want to make the class sealed here is link that explains how to do it.

EDITED: this is even better.

Upvotes: 0

vette982
vette982

Reputation: 4870

This site has a pretty good explanation of how to make template classes. Example:

// function template
#include <iostream>
using namespace std;

template <class T>
T GetMax (T a, T b) {
  T result;
  result = (a>b)? a : b;
  return (result);
}

int main () {
  int i=5, j=6, k;
  long l=10, m=5, n;
  k=GetMax<int>(i,j);
  n=GetMax<long>(l,m);
  cout << k << endl;
  cout << n << endl;
  return 0;
}

Use this in combination with this previous Stack Overflow question to achieve the sealed aspect of the class.

Upvotes: 1

Stuart Golodetz
Stuart Golodetz

Reputation: 20616

Like this:

template <typename TState, typename TTrigger>
class StateMachine
{
    //...
};

Upvotes: 3

Related Questions