我正在读一本关于模板的书。有一段示例代码使用折叠表达式使用运算符 ->* 遍历二叉树中的路径:
// define binary tree structure and traverse helpers:
struct Node {
int value;
Node* left;
Node* right;
Node(int i=0) : value(i), left(nullptr), right(nullptr) {
}
//...
};
auto left = &Node::left;
auto right = &Node::right;
// traverse tree, using fold expression:
template<typename T, typename... TP>
Node* traverse (T np, TP... paths) {
return (np ->* ... ->* paths); // np ->* paths1 ->* paths2 ...
}
int main()
{
// init binary tree structure:
Node* root = …Run Code Online (Sandbox Code Playgroud) 我从 c++ 入门知道我们可以通过以下方式使用 typedef:
typedef int mytype;
typedef int *mytype;
Run Code Online (Sandbox Code Playgroud)
不过下面的代码也编译通过了,好像新建了一个“rt”类型,我很好奇rt的类型是什么,这种typedef的常见用途是什么?
class A{
public:
int c;
};
typedef int A::* rt;
Run Code Online (Sandbox Code Playgroud) 拿这个代码:
struct mystruct
{
int var;
mystruct() : var(0) {}
};
int main()
{
mystruct ins;
int* p = &ins.var;
*p = 1;
}
Run Code Online (Sandbox Code Playgroud)
那么什么是类成员指针使用的具体非常好的例子呢?
int X::*p = &X::data; /* p contains offset */
X object;
X *objptr = new X;
int i = object.*p;
int j = objptr->*p;
Run Code Online (Sandbox Code Playgroud) 对于给定的结构:
struct foo
{
void fooFunc(){}
int fooVar = 0;
};
Run Code Online (Sandbox Code Playgroud)
我可以为函数创建一个调用wapper:std::mem_fn( &foo::fooFunc )这样我就可以将它传递给另一个方法并在一个对象上调用它.
我想知道是否有类似的调用包装器,但是对于成员变量.
例如,我在这里使用指向成员变量的指针,但我想使用一个调用包装器:
void bar( std::function< void( foo ) > funcPtr, int foo::* varPtr )
{
foo myFoo;
funcPtr( myFoo );
foo.*varPtr = 13;
}
Run Code Online (Sandbox Code Playgroud) 我有以下typedef独立非执行董事struct:
typedef struct
{
uint8_t u8Byte1; // This byte takes the needed values sometimes
uint8_t u8Byte2; // Not used
uint8_t u8Byte3; // This byte takes the needed values the other times
uint8_t u8Byte4; // Not used
} tstrMapMetadata;
Run Code Online (Sandbox Code Playgroud)
我有一个线程来填充(使用来自传感器的数据)这个结构并使用它的值之一:
while(true)
{
tstrMapMetadata * pstrMapMetadata = something();
if(pstrMapMetadata->u8Byte1 == SOMETHING) //<---- this line
{
//Do something special
}
}
Run Code Online (Sandbox Code Playgroud)
但是现在我有一个condition(线程中的常量),我想在其中比较标记的行u8Byte3而不是u8Byte1.
我当然可以
if(((condition) ? pstrMapMetadata->u8Byte1 : pstrMapMetadata->u8Byte3) == SOMETHING) //<---- this line …Run Code Online (Sandbox Code Playgroud) 这是编译和运行良好的完整代码:
# include <iostream>
using namespace std;
template<class T> class A { };
template<int i> class B { };
class C {
public:
int x;
};
class D {
public:
C y;
int z;
};
template<class T> void f (T) { cout << "T" << endl; };
template<class T> void f1(const T) { cout << "const T" << endl; };
temlate<class T> void f2(volatile T) { cout << "volatile T" << endl; };
template<class T> void g (T*) { cout …Run Code Online (Sandbox Code Playgroud)