Home > Mobile >  How to set the specific value to the concept template class explicit instantiation?
How to set the specific value to the concept template class explicit instantiation?

Time:01-24

I have codes as follow:

#include <concepts>
//Fibo Begins
    template <std::unsigned_integral num>
    struct Fibo {
        constexpr static std::size_t value = Fibo<num - 1>::value   Fibo<num - 2>::value;
    };

    template <>
    struct Fibo<1> {
        constexpr static std::size_t value = 1;
    };

    template <>
    struct Fibo<2> {
        constexpr static std::size_t value = 1;
    };
//Fibo ends

Compiler give out an error that argument 1 and 2 is invaild What's going on here? How can I fix it ?

CodePudding user response:

First, the syntax you are using is for a constrained type template parameter, not a non-type template parameter with constrained type. So the compiler is complaining that it expects a type as template argument, not a value.

For a non-type template argument with constrained type it should be std::unsigned_integral auto num instead.

But then 1 and 2 have type int. They are not unsigned and your type constraint correctly rejects them.

1u and 2u would for example be unsigned integers and accepted by the template parameter.

For a non-type template parameter with a placeholder type not only the value provided, but also the type, is significant.

It looks though as if you really want the type to be std::size_t, not any unsigned integral. So maybe just use that as type for the non-type template parameter instead of the constraint.

  •  Tags:  
  • Related