C++ 如何为 typedef 类型创建构造函数

标签 c++ typedef

在我的 C++ 项目中,我有一个名为 Expression 的类型

typedef std::function<uint64_t(uint64_t)> Expression;

我还有一个类似于构造函数的函数

Expression ExpressionConstructor(std::string Expr, MicroCodeDescriptor* descriptor) {
//implementation doesn't matter in this case
}

这段代码有效,我可以使用这样的表达式类型:

Expression expr= ExpressionConstructor(code, descriptor);

但是有没有什么方法可以为 Expression 声明一个构造函数,它在语法上像构造函数而不是像单独的函数一样工作,我不认为这从根本上是不可能的,因为构造函数只是具有返回类型的函数他们构造的类。

最佳答案

一个typedef不是一个新类型,它只是创建一个别名,您的 Expression仍然是std::function<uint64_t(uint64_t)>类型.

I don't see any reason why this is fundamentally impossible as constructors are just functions with the return type of the class they construct.

这从根本上来说并不是不可能的(从某种意义上说,规范不允许这样的事情),但是规范中没有给出这样的功能,所以你不能这样做。正如不可能向现有类型添加新成员函数一样。

关于C++ 如何为 typedef 类型创建构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64970184/

相关文章:

C++ 重载 wchar_t 赋值运算符

c++ - 如何与 CRTP 一起使用?

c++ - 扩展 typedef struct(兼容 VC++11)

c - 将枚举值切换为位标志

c++ - 无法与 typedef 成为 friend : any particular reason?

c - Typedef 结构问题

c++ - 有没有一种通用的方法可以用 SFINAE 否定 decltype 条件?

c++ - Qpid 质子 C++ - 质子::make_work

c++ - 这是动态分配float变量的正确方法吗?

c++ - 从 Lua 修改 main() 中的 C++ 数组,无需额外分配