避免显式函子模板类型
Avoiding explicit functor template type
本文关键字:类型 更新时间:2023-10-16
我在玩函子。我正在使用下面的标准示例:
class C {
public:
template <typename Func>
void foo(Func fun)
{
fun();
}
};
struct S {
void operator()() { printf ("in Sn"); }
};
....
C myClass;
myClass.foo (S());
这工作得很好,我不需要在调用 foo() 时显式提供 S 模板类型,它只是解决了。但是假设我想将函子存储为成员变量并在以后调用它:
class C {
public:
template <typename Func>
void foo(Func fun) {
_myFunc = fun;
}
void someOtherThing() {
_myFunc();
}
private:
WHAT_IS_THIS_TYPE _myFunc;
};
我现在需要将整个类制作为模板吗?如果是这样,编译器是否可以像推断单个函子一样推断模板类型,还是必须显式提供它?谢谢。
您可以使用 std::function(在 C++11 中)或 boost::function 来存储可调用的对象(函数、函子)。它实现了类型擦除模式。
class C {
public:
template <typename Func>
void foo(Func fun) {
_myFunc = fun;
}
void someOtherThing() {
_myFunc();
}
private:
std::function<void()> _myFunc;
};
这是一种手工制作的方法,可以避免将类C
作为模板:
struct C {
template <typename Func>
void foo(Func fun) {
_myFunc = static_cast <void*>(&fun);
stub = call <Func>;
}
void someOtherThing() {
stub(_myFunc);
}
private:
void* _myFunc;
void (*stub)(void*);
template <typename F>
static void call(void* f) {
(*static_cast <F*>(f))();
}
};
struct S {
void operator()() { std::cout << "in S" << std::endl; }
};
int main()
{
S s;
C myClass;
myClass.foo(s);
myClass.someOtherThing();
}
当你调用foo()
时,类型Func
被"存储"在模板静态函数call
中,一个指向(一个instaiation)的指针,它存储在stub
中。后者被someOtherThing
调用来实际调用_myFunc
,这只不过是普通的void*
。为此,_myFunc
首先被投射回正确的类型,这只有在call
体内才知道。
唯一的问题是,使用指向函数的指针,stub(...)
调用不能内联。
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 类中的字符串不命名类型