简体   繁体   中英

Calling a function by class file name

I have the function

wstring trim(wstring& str)
{
  string::size_type pos = str.find_last_not_of(' ');
  if(pos != string::npos) {
    str.erase(pos + 1);
    pos = str.find_first_not_of(' ');
    if(pos != string::npos) str.erase(0, pos);
  }
  else str.erase(str.begin(), str.end());

  return str;
}

in the file strhelper.cpp.

I would like to ask if it is possible to call the function like this:

strhelper.trim(...

or

strhelper::trim(...

This would help me work faster. Currently when I type "trim", the VS IDE offers me many functions that I am not looking for. If I could restrict the function name search to my file, VS would not offer so many undesired results, but I have not found a way to do that yet.

Thank you.

The latter is possible:

strhelper::trim(...

If you simply wrap the function declaration and definition in a namespace scope:

namespace strhelper {
    wstring trim(wstring& str){ /* your code here*/ }
}

That's kind of what namespace are for:

namespace strhelper
{
    wstring trim(wstring& str)
    {
        ...
    }
}

You also need to remember to put the function prototype in the namespace as well in your header file:

namespace strhelper
{
    wstring trim(wstring& str);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM