Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify non-deducible template parameters on a constructor? [duplicate]

Tags:

c++

templates

It's possible to give a templated constructor template parameters that cannot be deduced:

struct X
{
    int i;

    template<int N>
    X() : i(N)
    {
    }
};

How would you use such a constructor? Can you use it at all?

like image 797
zneak Avatar asked Dec 10 '25 20:12

zneak


1 Answers

No, you can't specify constructor template arguments. There are a few alternatives.

  1. As indicated in the comments by @KerrekSB, you can give the constructor template a std::integral_constant parameter, which when passed as an argument, will deduce N:

Code:

#include <cassert>
#include <type_traits>

struct X
{
    int i;

    template<int N>
    X(std::integral_constant<int, N>) : i(N)
    {
    }
};

int main()
{
    std::integral_constant<int, 6> six;
    X x(six);
    assert(x.i == 6);
}

Live Example

  1. You can write a dedicated make_X<N> template wrapper that hides the integral_constant boiler-plate:

Code:

template<int N>
X make_X()
{
    return X(std::integral_constant<int, N>{});        
}

int main()
{
    auto y = make_X<42>();
    assert(y.i == 42);
}

Live Example

like image 97
TemplateRex Avatar answered Dec 13 '25 09:12

TemplateRex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!