Overloaded function template with different return types

Discussion in 'C++' started by hbdevelop1, Feb 2, 2014.

  1. hbdevelop1

    hbdevelop1 Guest

    Hello all,

    In functional\hash\hash.hpp in Boost ver. 1.54.0, there are many overloads of the template function hash_value where only the return type changes (see a snapshot of code at the end of this post).

    1-
    How does the compiler determine which version of the hash_value it should use in a call?
    For example, for struct hash<unsigned int>::eek:perator() it uses the version that returns boost::hash_detail::basic_numbers<T>::type.
    Why ? What is the rule it applies ?

    2-
    How can I force the compiler to use a certain version of hash_value ?

    Thank you very much in advance

    ----- code from boost\functional\hash\hash.hpp ------

    namespace boost
    {
    namespace hash_detail
    {
    struct enable_hash_value { typedef std::size_t type; };

    template <typename T> struct basic_numbers {};
    template <typename T> struct long_numbers;
    template <typename T> struct ulong_numbers;
    ...
    template <> struct basic_numbers<unsigned int> :
    boost::hash_detail::enable_hash_value {};
    ...
    template <typename T> struct long_numbers2 {};
    template <typename T> struct ulong_numbers2 {};
    template <typename T> struct long_numbers : long_numbers2<T> {};
    template <typename T> struct ulong_numbers : ulong_numbers2<T> {};
    ...
    }

    //version 1 of hash_value
    template <typename T>
    typename boost::hash_detail::basic_numbers<T>::type hash_value(T v)
    {
    return static_cast<std::size_t>(v);
    }

    //version 2 of hash_value
    template <typename T>
    typename boost::hash_detail::long_numbers<T>::type hash_value(T v)
    {
    return hash_detail::hash_value_signed(v);
    }

    //version 3 of hash_value
    template <typename T>
    typename boost::hash_detail::ulong_numbers<T>::type hash_value(T v)
    {
    return hash_detail::hash_value_unsigned(v);
    }
    ....

    template <> struct hash<unsigned int> :
    public std::unary_function<unsigned int, std::size_t>
    {
    std::size_t operator()(unsigned int v) const
    {
    return boost::hash_value(v); //uses version 1 of hash_value
    }
    };
     
    hbdevelop1, Feb 2, 2014
    #1
    1. Advertisements

  2. hbdevelop1

    Ken-Yi Lee Guest

    You can take a look at the namespace: boost::hash_detail. A struct, enable_hash_value, is used to determine the bindings. For example, bool, char and unsigned char types are listed in basic_numbers.
    You can use casting.

    Feis
     
    Ken-Yi Lee, Feb 2, 2014
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.