How do make_pair know the types of its arguments?

The definition of make_pair in the header of the MSVC ++ utility:

template <class _Ty1,
 class _Ty2> inline
 pair <_Ty1, _Ty2> make_pair (_Ty1 _Val1, _Ty2 _Val2)
 {// return pair composed from arguments
 return (pair <_Ty1, _Ty2> (_ Val1, _Val2));
 }

I use make_pair all the time, but without putting argument types in angle brackets:

    map <string, int> theMap;

    theMap.insert (make_pair ("string", 5));

Do I need to indicate make_pairthat the first argument std::string, not char*?

How does he know?

+3
source share
4 answers

(.. make_pair<…>) , ++ 03 Β§14.8.2. :

, . , , .

, " ", , .

.

  • make_pair a pair<char const*, int>,
  • template<class U, classV> pair<string,int>::pair( pair<U,V> const & ) U = char*, V = int -,
  • string::string(char*).
+12

. make_pair < char *, int > (, , < char const *, int > ).

, , :


template < typename Other1, typename Other2 > 
pair(pair<Other1,Other2>& other) 
  : first(other.first), second(other.second)
{}

-, . , < std::string, int > < char *, int > - , .

+9

make_pair() , .

. SO:

+1

It relies on the fact that the std :: string constructor accepts const char *. It doesn't matter if this constructor is std :: string explicit or not. The template subtracts the type and uses the pair copy constructor to convert it. It also doesn't matter if the constructor is an explicit pair.

If you turn the std :: string constructor into:

class string
{
public:
    string(char* s)
    {
    }   
};

you will get this error:

/usr/include/c++/4.3/bits/stl_pair.h: In constructor β€˜std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&) [with _U1 = const char*, _U2 = int, _T1 = const string, _T2 = int]’:
foo.cpp:27:   instantiated from here
/usr/include/c++/4.3/bits/stl_pair.h:106: error: invalid conversion from β€˜const char* const’ to β€˜char*’
/usr/include/c++/4.3/bits/stl_pair.h:106: error:   initializing argument 1 of β€˜string::string(char*)’

The constructor looks like this:

  template<class _U1, class _U2>
    pair(const pair<_U1, _U2>& __p)
    : first(__p.first),
      second(__p.second) { }

The copy constructor is as follows:

template<class _U1, class _U2>
pair(const pair<_U1, _U2>& __p)
    : first(__p.first),
      second(__p.second) { }
+1
source

Source: https://habr.com/ru/post/1741854/


All Articles