【发布时间】:2021-03-22 19:09:14
【问题描述】:
我们实现了一个将回调传递给对象实例成员函数的系统。这很好用,请参见下面的代码。问题是实现的当前状态只处理非常量成员函数。
下面的代码编译并演示了系统正在运行。只要包含/* const */,它就不再编译。
错误消息本地化不是英文,但第一条消息是“不完整类型”。
从逻辑上讲,对 const 成员函数的调用不应该比对非 const 成员函数的调用更受限制,因此看起来基本目标是明智的。 很明显,const 成员的类型与非 const 成员的类型不同。问题是我们没有找到一种方法向编译器表达代码对 const 成员也有效。
在所示的 WrapP 中,我们可以在哪里以及如何表示 const 是可以接受的?是否可以定义一个同时接受 const 和 non-const 成员函数的模板?
#include <algorithm>
#include <functional>
#include <iostream>
using std::cout;
using std::endl;
template <auto F>
struct WrapP;
template <typename T, typename R, typename ... Args, R(T::* F)(Args...)>
struct WrapP<F> {
T* obj_;
WrapP(T* instance) : obj_(instance) {}
auto operator()(Args... args) const {
return (obj_->*F)(args...);
}
};
struct foo {
// Const below is needed, but could not be activated.
auto bar(double) /* const */ -> int {
return 314; };
};
int main() {
foo x;
// Create a functor for foo::bar
WrapP<&foo::bar> fp{ &x };
// Call the functor.
std::cout << fp( 3.14159265 ) << std::endl;
return 0;
}
【问题讨论】:
标签: c++ variadic-templates template-argument-deduction