Hanna Khalil
Hanna Khalil

Reputation: 1055

auto deduction of part of template types

I want to write simple template function which returns n lsb bits of given number, where n is template parameter, and I would like it to work with uint8_t, uint16_t, uint32_t, uint64_t. So I though of:

template<size_t n, typename T>
inline T align_to(const T& num) {
    static_assert(std::is_integral<T>::value, "integer required");
    static_assert(n < sizeof(T) * 8, "overflow");
    return num & (Ones(n));
}

The problem is that typical usage would be:

align_to<4, uint64_t>(some_uint64_t_var)

where I would like the type uint64_t to be deduced automatically by the compiler and I of course want to provide n. so I'm looking for a way in which compiler deduces only part os template arguemtns.

Upvotes: 0

Views: 85

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

Your align_to function will automatically deduce T. It can be deduced by passing num as an argument: example on wandbox.

template <std::size_t n, typename T>
inline T align_to(const T& num)
{
    // ...
}

int main()
{
    std::int32_t x = 100;
    align_to<16>(x); // `T` deduced as `std::int32_t`
}

See cppreference - template argument deduction for an overview of the rules.

Upvotes: 2

Related Questions