c++constructorconstexpr

How to pass constexpr to constructor?


I have a template A with non-type parameter:

template <int param = 0>
class A
{
public:
    static constexpr void print()
    {
        std::cout << param << std::endl;
    }
};

And I have a class B, in the constructor of which I'm going to use the template A.

class B
{
public:    
    B()
    {
        A<> a{};
    }
};

To initialise a I want to use constexpr int from main function.

int main()
{
    constexpr int val = 123;

    B b{};
}

In case of general function, I could just turn it into the template, but as far as I know it does not work for constructors. At least it didn't work for me.

Making the entire class B into a template is not an option, I need it to remain a class.

Is it possible to pass val from main to class B constructor?


Solution

  • You might use std::integral_constant to pass that constant:

    class B
    {
    public:
        template <int N>
        explicit B(std::integral_constant<int, N>)
        {
            A<N> a{};
        }
    };
    
    int main()
    {
        constexpr int val = 123;
    
        B b{std::integral_constant<int, val>{}};
    }
    

    Demo