gpt4 book ai didi

c++ - 指向成员的指针作为模板参数

转载 作者:太空狗 更新时间:2023-10-29 23:51:51 25 4
gpt4 key购买 nike

我使用 Visual C++ 2012。我想使用指向另一个函数的指针来参数化模板函数。这一切都在类之外很好地工作:

int add(int a, int b) {
return a + b;
}
typedef int (*func)(int a, int b);
template<func F> int do_it(int a, int b) {
return F(a, b);
}
int foo(int a, int b) {
return do_it<add>(a, b);
}

Visual C++ 2012 对其进行了完美的编译和优化。

现在,我将它放在一个类中并针对指向成员的指针进行调整:

struct S {
int add(int a, int b) {
return a + b;
}
typedef int (S::*func)(int a, int b);
template<func F> int do_it(int a, int b) {
return F(a, b); // <-- here be error!
}
int foo(int a, int b) {
return do_it<&S::add>(a, b);
}
};
S s;

int bar(int a, int b) {
return s.foo(a, b);
}

但这给了我一个编译器错误:

Microsoft (R) C/C++ Optimizing Compiler Version 17.00.51106.1 for x86
Copyright (C) Microsoft Corporation. All rights reserved.

x2.cpp
x2.cpp(7) : error C2064: term does not evaluate to a function taking 2 arguments
x2.cpp(10) : see reference to function template instantiation 'int S::do_it<int S::add(int,int)>(int,int)' being compiled

知道为什么以及如何解决它吗?

最佳答案

成员指针的语法仍然适用。你应该写:

typedef int (S::*func)(int a, int b);
template<func F> int do_it(int a, int b) {
return (this->*F)(a, b);
}

使用指向成员的指针总是需要将对象与其相关联 - 在这里,您可以在 this 上调用指针。

关于c++ - 指向成员的指针作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18573451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com