用相同的args声明两个构造函数的最理想的方法是什么? [英] What's the most idotomatic way of declaring two constructors with the same args?
问题描述
作为一个例子,我有一个名为 File
的类。现在,文件可以二进制或文本形式打开。我的构造函数当前为 File(const char * filename)
。让我们假设open的实现是完全不同的二进制和文本。我该怎么构造呢?
As an example lets say I have a class called File
. Now file can be opened as binary or text. My constructor is currently File(const char*filename)
. Let's suppose the implementation of open is completely different binary and text. How the heck do I construct this?
我曾考虑使用静态函数,但不想返回指针。我可以传递一个指针,但我宁愿不允许在没有实际初始化的情况下构造一个类。
I thought about using a static function but I don't want to return a pointer. I could pass in a pointer but I rather not allow a class be constructed without actually initializing it.
我当时在考虑在构造函数中使用枚举或布尔值,但是感觉对我不对(以及我这样做的方式)。我可以为二进制和文本使用不同的类名称,并且都继承一个基本实现(或其他实现),即使唯一的区别是构造函数。
I was thinking about having an enum or bool in the constructor but it feels 'wrong' to me (and the way I may do this). I could have a different class name for binary and text and have both inherit a base implementation (or the other implementation) even though the only difference is the constuctor.
这是什么
推荐答案
两种惯用的方法是工厂函数(没有强制您返回指针的方法)?或标签分发(在标准库中使用,例如,在 std :: variant
)。
Two idiomatic ways are a factory function (nothing forces you to return a pointer), or tag dispatching (which is used in the standard library, for example in std::variant
).
// Factory functions
struct File {
static File openText(char const *filename);
static File openBinary(char const *filename);
};
// Tag dispatching
struct open_as_binary_t {} constexpr open_as_binary;
struct open_as_text_t {} constexpr open_as_text;
struct File {
File(char const *filename, open_as_binary_t);
File(char const *filename, open_as_text_t);
};
这篇关于用相同的args声明两个构造函数的最理想的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!