Search code examples
c++templatescompile-time

template parameter (either 1 or 2): any way to set it at runtime (compile-time if,...)?


#include <iostream>
#include <fstream>

template <unsigned int dim>
class MyClass
{
    public:
    private:
        double data[dim]; 
        //many more members that depend on dim
};

int main()
{
    std::fstream myfile("path_to_my_file.txt", std::ios_base::in);

    unsigned int dim;

    myfile >> dim; //depending on the file content, dim=1 or dim=2

    std::shared_ptr<MyClass<dim>> ptr;

    
}

I have a pointer to a class with template parameter dim (an integer) In my case, dim is either 1 or 2.

I know that template parameters must be known at compile time. But, is there a way to tell the compiler to compile both MyClass<1> and MyClass<2> and choose the desired class at runtime?


Solution

  • So the question if still hard to answer, but I'll present a possible solution based on polymorphism. A template based solution might also be possible but the choice between these two is hard to judge given the lack of context.

    class Base
    {
    public:
        virtual ~Base() {};
        virtual void something() = 0;
        // more pure virtual methods
    };
    
    template <unsigned int dim>
    class MyClass : public Base
    {
    public:
        void something() override;
        // overrides for other pure virtual methods
    private:
        double data[dim]; 
        //many more members that depend on dim
    };
    
    
    int main()
    {
        int dim = ,,,;
    
        shared_ptr<Base> ptr;
        if (dim == 1)
            ptr = make_shared<MyClass<1>>();
        else
            ptr = make_shared<MyClass<2>>();
        ptr->something();
    }