Today I tried to study some piece of code and I am stuck with this line.
std::vector<std::string(SomeClassInterface::*)()> ListOfFnPointers;
what is the meaning of this std::string constructor? I went through this but I have no idea what it means.
It is used in the code as,
if (!ListOfFnPointers.empty())
{
std::vector<std::string> StringList;
for (auto Fn : ListOfFnPointers)
{
StringList.push_back((pSomeClassObj->*Fn)());
}
...
}
pSomeClassObj->*Fn
?It is used to construct a string object. and initializing its value depending on the constructor version used.
C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
std::string::string. Constructs an empty string, with a length of zero characters. Constructs a copy of str. Copies the portion of str that begins at the character position pos and spans len characters (or until the end of str, if either str is too short or if len is string::npos).
The std::string type is the main string datatype in standard C++ since 1998, but it was not always part of C++. From C, C++ inherited the convention of using null-terminated strings that are handled by a pointer to their first element, and a library of functions that manipulate such strings.
It has nothing to do with std::string
constructor.
std::string(SomeClassInterface::*)()
is type of pointer to member function, the member function belongs to class SomeClassInterface
, returns std::string
, takes no parameters.
->*
is pointer-to-member access operator (and also .*
). (pSomeClassObj->*Fn)()
will call the member function on pSomeClassObj
, which is supposed to be a pointer with type SomeClassInterface*
.
It's not a constructor it's a pointer to function without parameters returning std::string.
for (auto Fn : ListOfFnPointers)
{
StringList.push_back((pSomeClassObj->*Fn)());
}
Push back's above are working because (pSomeClassObj->*Fn)() is a call to these functions and result is std::string.
UPDATED:
It is declaration of std::vector of pointers to function. Each function belongs to SomeClassInterface, takes no parameters and return std::string.
In case of this code (pSomeClassObj->*Fn)() calls the function of objects pSomeClassObj where Fn is a pointer to this function and member of pSomeClassObj.
If you use C++11
,you can write code like this:
using FunctionPointer = std::string (SomeClassInterface::*) ();
std::vector<FunctionPointer> ListOfFnPointers;
you can read this link: http://en.cppreference.com/w/cpp/language/type_alias
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With