1

In C++ is there a way to get the name of a vector that was passed to a function inside the function?

#include<bits/stdc++.h> 
using namespace std; 

void func(vector<int> &vect) 
{ 

std::cout << "The name of vector passed to func is " << vect.GETNAME();
} 

int main() 
{ 
    vector<int> vectorName; 

    func(vect); 

    return 0; 
} 

I expect to see "The name of vector passed to func is vectorName".

I have tried googling the error and understand that you cannot get object names in c++ but can I modify the vector class to add a getName() method?

cherry aldi
  • 319
  • 1
  • 6
  • 1
    Explain what kind of output you expect. An address? A string? – fzd Oct 15 '18 at 15:53
  • https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h –  Oct 15 '18 at 15:55
  • 1
    Vector does not have a .`GETNAME()` member function and the language does not have reflection. – Ron Oct 15 '18 at 15:56
  • 1
    Why do you think you need the name of the vector? –  Oct 15 '18 at 15:56
  • If you change the function to accept a string as its first argument, you could use Stringification (http://gcc.gnu.org/onlinedocs/gcc-3.4.3/cpp/Stringification.html) and a macro. – Reborn Oct 15 '18 at 16:13
  • If you need a data structure that acts like `std::vector` **and** carries some text around for identification you need to write it yourself. It's not hard. – Pete Becker Oct 15 '18 at 16:20
  • 1
    Side note: Identifiers, the names used to refer to "Stuff", are casualties of the build process. The computer has no need for `MyVar`, it's just a memory location or an offset from a memory location, so they're usually discarded. You may be able to get something similar to what you want with a [`std::map`](https://en.cppreference.com/w/cpp/container/map) or similar mapping structure. – user4581301 Oct 15 '18 at 16:36
  • 1
    Unrelated. Do not use `#include` ([why](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h)) and avoid `using namespace std;` ([why](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)). When you put the two together, they magnify each others worst effects. – user4581301 Oct 15 '18 at 16:37

1 Answers1

4

No, there is not. At least not for std::vector and ordinary functions. Behind the scenes the vect reference is just a pointer to somewhere in memory. Nothing in the C++ standard gives you the option to retrieve the name of something on the call site (it might not even exist - what is the name of {1, 2}?).

Max Langhof
  • 22,398
  • 5
  • 38
  • 68