通过显式构造函数初始化数组 [英] Initializing array through explicit constructor
问题描述
我正在编写一个类,该类具有带const char*
参数的显式构造函数.出于这个问题的意图和目的,它看起来像这样:
I'm writing a class that has an explicit constructor taking a const char*
argument. For the intents and purposes of this question it looks like this:
struct Symbol
{
Symbol()=default;
explicit Symbol(const char*);
};
现在,出于文档目的,我想编写一个示例来初始化数组(array/vector/list-我不在乎确切的类型),并且我需要使示例尽可能简洁明了.理想情况下,它看起来应该像这样:
Now I want to write an example for documentation purposes that initializes an array (array/vector/list - I don't care about the exact type) and I need the example to be as clear and concise as possible. Ideally it would look like this:
Symbol symbols[] = { "a", "b", "c"};
由于显式关键字而无法编译,因此我不准备使构造函数隐式化.
That does not compile because of the explicit keyword and I am not prepared to make the constructor implicit.
如何使这项工作有效,重点在于使示例代码尽可能具有表现力?
How can I make this work, with the focus of making the example code as expressive as possible?
在Caleth的一点帮助下,我寻求了Bolov的解决方案:
I went for Bolov's solution with a little help from Caleth:
struct Symbol
{
Symbol();
explicit Symbol(const char*);
template <class... Args>
static std::array<Symbol, sizeof...(Args)> Array(Args... args)
{
return {Symbol{args}...};
}
};
int main()
{
auto symbols = Symbol::Array("a", "b", "c");
}
推荐答案
好,您的构造函数是显式的,因此您需要这样使用它:
Well, your constructor is explicit so you need to use it as such:
Symbol symbols[] = {Symbol{"a"}, Symbol{"b"}, Symbol{"c"}};
gcc和clang都是copy/move构造函数,并且由于C ++ 17是必需的行为,因此没有性能开销.
Both gcc and clang both the copy/move constructor and since C++17 that is the required behavior so there is no performance overhead.
如果您真的想保留构造函数explicit
并能够创建一个数组而无需为每个元素明确声明,则可以创建一个辅助函数:
If you really want to keep the constructor explicit
and be able to create an array without explicitly stating it for every element then you can create a helper function:
template <class... Args,
class Enable = std::enable_if_t<(... && std::is_same_v<Args, const char*>)>>
auto make_symbols(Args... args) -> std::array<Symbol, sizeof...(Args)>
{
return {Symbol{args}...};
}
并像这样使用它:
auto symbols = make_symbols("a", "b", "c");
再次取消移动/副本.
make_symbols
函数使用C ++ 17功能来检查参数类型.如果您需要以前的标准版本(包括C ++ 11)的约束,请参见以下答案限制可变参数模板参数.或者,根据您的需要,也可以选择取消支票.
The make_symbols
function uses C++17 features for checking the arguments types. If you need the constraint for a previous standard version (including C++11) see this answer Restrict variadic template arguments. Or, depending on your needs, removing the check can also be a choice.
这篇关于通过显式构造函数初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!