I
I
iihaarr2022-04-10 14:23:26
C++ / C#
iihaarr, 2022-04-10 14:23:26

How to use patterns to check that two numbers are equal?

I tried like this:

template<typename R, typename C, typename std::enable_if<std::is_arithmetic<R>::value && std::is_arithmetic<C>::value>::type = true>
struct are_values_equal
{
    constexpr static bool value = R == C;
};

So:
template<const std::size_t R, const std::size_t C>
struct are_values_equal
{
    constexpr static bool value = R == C;
};

But in the first case, as I understand it, the compiler cannot understand that two numbers are being compared, and in the second, an error:
a non-type template parameter cannot have type
In both cases, I pass 2 template parameters of type const std::size_t.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2022-04-10
@wataru

Answering a question from the comments. You can do this:

template <int a, int b>
class A {
    public:
    template<bool tmp = true>
    typename std::enable_if<a==b && tmp, int>::type F() {
       return 1;   
    }
};

...

A<1,1> a;
std::cout << a.F();  // OK.
A<2,100> b;
std::cout << b.F(); // Ошибка A<2,100> не имеет метода F().

It's hard for me to explain why it works, but I'll try.
First, the method must be wrapped in a template, because if there is an error, then the template for your Matrix type is not instantiated, and it should be even if the dimensions are not equal.
Next, I would like it to just work like this:
template<>
 typename std::enable_if<a==b, int>::type F()

Everything is clear here, enable_if has no type if a is not equal to b. The template cannot be instantiated in any way and the method should not be generated. But that would be too easy.
Instead, you need to add some kind of unnecessary tmp template parameter there, and be sure to use it in enable_if. This is because if this template does not use a template parameter in any way, then SFINAE does not work, and a compilation error pops up.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question