c++templatesclass-constructors

Using template to create default constructor in C++ in main


Is there a way to use templates to create a standard constructor of class in your main?

If I have a class:

myclass.h

class myClass
{
private:
    float a;
public:
    myClass(float _a) {a = _a;}
    float getA(){return a;}
    ~myClass() {}
};

Is there a way to template this in your main like so:

main.cpp

#include "myclass.h"

typedef myClass<5.0> Dummy

int main(int argc, char const *argv[])
{
    // EDIT: removed the following typo
    // Dummy dummy();
    Dummy dummy;
    std::cout << dummy.getA() << std::endl;
    return 0;
}

Which should output:

> 5.0000000

So that one may define in the main a standard way to construct the instances.


Solution

  • You are possibly better off just using a default instance which you make copies of whenever you need a new instance:

    #include "myclass.h"
    
    Dummy myClass(5.0);
    
    int main(int argc, char const *argv[])
    {
        myClass dummy1 = Dummy;
        std::cout << dummy1.getA() << std::endl;
        myClass dummy2 = Dummy;
        std::cout << dummy2.getA() << std::endl;
        return 0;
    }