1

I am facing the following problem: I am trying to create a function to print a generic pointer information on the screen. This is the code:

#include <iostream>
#include <string>

template <class T_str, class T>
std::basic_string<T_str> ptr( T* ptr )
 {
  std::basic_ostringstream<T_str> oss;
  oss << "Value: " << ptr << "\n";
  oss << "Direction: " << &ptr << "\n";
  return oss.str();
 }

int main()
 {
  int *p;
  std::cout << ptr( p );
 }

But I got the following error:

other.cpp: In function ‘int main()’:
other.cpp:15:19: error: no matching function for call to ‘ptr(int*&)’
   15 |   std::cout << ptr( p );
      |                ~~~^~~~~
other.cpp:4:26: note: candidate: ‘template<class T_str, class T> std::__cxx11::basic_string<_CharT> ptr(T*)’
    4 | std::basic_string<T_str> ptr( T* ptr )
      |                          ^~~
other.cpp:4:26: note:   template argument deduction/substitution failed:
other.cpp:15:19: note:   couldn’t deduce template parameter ‘T_str’
   15 |   std::cout << ptr( p );

I don't understand what is the problem. Can you help me? Thanks.

Gianluca Bianco
  • 656
  • 2
  • 11
  • Note that even if this succeeds, `prt(p)` will be **undefined behavior**. See dupe: [Calling function with variable that is being initialized](https://stackoverflow.com/questions/73643920/calling-function-with-variable-that-is-being-initialized/73643982#73643982) – Jason Sep 17 '22 at 13:35
  • @JasonLiam is there a way to print these information correctly? – Gianluca Bianco Sep 17 '22 at 13:36
  • You are missing `#include `. Also since p is uninitialized you have UB as noted by @JasonLiam. – wohlstad Sep 17 '22 at 13:36
  • 1
    The compiler can't deduce `T_str`, `std::cout << ptr( p );` should compile. – john Sep 17 '22 at 13:36
  • @john The problem is that OP hasn't included `sstream` and `T_str` can't be deduced. Also, `p` is uninitialized as mentioned earlier. – Jason Sep 17 '22 at 13:37
  • 1
    @JasonLiam That is another problem, but mine is a problem too. – john Sep 17 '22 at 13:38
  • 1
    `ptr(&p)` should make your function callable. It won't do the correct thing, but that's another issue. – Some programmer dude Sep 17 '22 at 13:38
  • @john is right! Thanks! Please do a full answer so I can upvote it and choose it as the correct one – Gianluca Bianco Sep 17 '22 at 13:39
  • What do you mean by "Direction" ? By printing `&ptr` you print the address of the pointer itself (which will be somewhere on the callstack). – wohlstad Sep 17 '22 at 13:39
  • @john I see. I tried in one compiler and it compiled after including `sstream`. Then i tried again and it failed. So yes, `T_str` cannot be deduced. – Jason Sep 17 '22 at 13:40

0 Answers0