chapel1337
chapel1337

Reputation: 17

how do i compare types in c++?

i'm trying to divide two integers, and if the output is not an integer, it doesn't continue. for some reason this refuses to work no matter what i try.

    int numeratorOutput{};
    int denominatorOutput{};

    for (int i{ 2 }; i < 100; ++i)
    {
        auto test = numerator / i;
        auto test2 = denominator / i;

        if (typeid(test) == typeid(int) && typeid(test2) == typeid(int))
        {
            cout << i << '\n';
            cout << "yes\n\n";

            numeratorOutput = numerator / i;
            denominatorOutput = denominator / i;

            break;
        }
        else
        {
            cout << "no\n";
        }
    }

i tried typeid, sizeof, is_same, etc.; but it let to no avail

Upvotes: -1

Views: 154

Answers (1)

user19946454
user19946454

Reputation:

how do i compare types in c++?

In your given example, you can use decltype along with std::is_same to check if test is the same as int and test2 is the same as int as shown below:

#include <type_traits>

static_assert(std::is_same_v<decltype(test), int>);
static_assert(std::is_same_v<decltype(test2), int>);

Upvotes: 2

Related Questions