简体   繁体   中英

setting typename default value for vardiac and normal template

template<typename T, T... Xs> class Nzm
{
private:
template<typename... Ts> static constexpr T Max(Ts... xs);

template<typename Tx> static constexpr T Max(Tx x)
{
    return x;
}

template<typename T1, typename T2, typename... Ts> static constexpr T Max(T1 x, T2 y, Ts... xs)
{
    return y > x ? Max<T2, Ts...>(y, xs...) : Max<T1, Ts...>(x, xs...);
}

public:
static const T Z = Max(Xs...);
};


int main() {

static_assert(Nzm<int,1,2,3,4,5,6>::Z==5,"XYZ");

return 0;
}

I already know that all the typename are going to be int and I only want to use

Nzm<1,2,3,4,5,6> 

instead of

Nzm<int,1,2,3,4,5,6> 

this is for compile time execution no code or tips for making it runtime. is this possible? to set all this typename to int ?

The quick solution is to use a using declaration to get ride of the int.

template<int... x>
using helper =  Nzm<int, x...>;

int main() {

    static_assert(helper<1, 2, 3, 4, 5, 6>::Z == 6, "XYZ");

    return 0;
}

Another (better) way is to modify Nzm and replace all the typename templates with int templates. You're left with a redundancy between the parameters and template arguments, so you can get rid of the parameters.

template<int... Xs> class Nzm
{
private:
    template<int x> static constexpr int Max()
    {
        return x;
    }

    template<int x, int y, int... rest> static constexpr int Max()
    {
        return x > y ? Max<x, rest...>() : Max<y, rest...>();
    }

public:
    static const int Z = Max<Xs...>();
};

int main() {

    static_assert(Nzm<1, 2, 3, 4, 5, 6>::Z == 6, "XYZ");

    return 0;
}

If you want a template that accepts a parameter pack of int s, have yourself such a template:

template<int ...Is> class Nzm {
  // Your implementation follows
};

Templates can accept parameters which aren't types (among them parameters which are integers), and consequently they can accept analogous parameter packs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM