lundi 16 septembre 2019

How do I use a template to create different constructors in C++?

A brief conceptual example of what I'm asking:

#include<iostream>
#include<string>


// Example tempate class scenario
template<int N>
class Example
{
    switch (N)
    {
    case 0:
        Example() { std::cout << "Interesting..." << std::endl; }
        break;

    case 1:
        Example () { std::cout << "Wow, didn't expect that!" << std::end; }
        break;

    case 2:
        Example() { std::cout << "Hmm..." << std::endl; }
        break;

    default:
        Example() { std::cout << "Not a valid value for N!" << std::endl; }
        break;
    }
}

// Very basic main to call constructors
int main()
{
    Example<0> a;
    Example<1> b;
    Example<2> c;
    Example<3> d;

    return 0;
}

If this method does work perfectly fine, then I have some more questions:

  1. How would you do this with if statements instead of switches (for, e.g., strings instead of ints)?
  2. Is there a better way to go about this?
  3. How would you pass parameters into constructors if, e.g., each constructor in each case took different parameters?

Aucun commentaire:

Enregistrer un commentaire