c++ - 使用可变参数模板将指针传递给成员

标签 c++ c++17

考虑下面的代码:

struct A {int x; bool y; double z;};

template <class T>
void func(T A::*fieldPtr) {}

int main() { func(&A::x); }

是否有可能使 func 接受多个指向具有可变参数模板的 A 成员的指针?所以可以这样使用:

func(&A::x, &A::y);
func(&A::x, &A::y, &A::z);
...

我的第一个想法是:

    template <class... Args>
    void func(Args... A::*fieldPtr);

但它不编译。

编辑1

使用 MSVC 2017 我得到:错误 C2988:无法识别的模板声明/定义

使用 Clang:请参阅 live example .

最佳答案

Is it possible to make func accept multiple pointers to A members with variadic templates?

My first idea was this:

 template <class... Args>
 void func(Args... A::*fieldPtr);

but it does not compile.

试试

template <class ... Ts>
void func(Ts A::*...fieldPtr) { /* do something with fieldPtr... */ }
// ..............^^^

关于c++ - 使用可变参数模板将指针传递给成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58509459/

相关文章:

C++ Friend 函数不能访问私有(private)成员;错误 2248

c++ - 我们什么时候必须在派生类c++中定义析构函数

c++ - `std::any_cast` 返回拷贝

C++ 最佳实践 : Pass use-only (not stored) lambda argument to function by const-reference or by forwarding-reference (a. k.a.通用引用)

c++ - CRTP 模式不会触发完整模板实例化

c++ - vkCreateInstance 导致段错误

c++ - 无法在 C++ 中初始化 Matlab dll

c++ - 如何从就地临时变量初始化非静态私有(private)模板成员变量,即不进行复制或移动?

c++ - optional<T> 进入 C++ 标准的含义

c++ - 嵌套类的类内 friend 是否可以访问外部类成员?