gpt4 book ai didi

c++ - 使用默认参数 boost list_of

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:21:36 27 4
gpt4 key购买 nike

我在使用以下结构时遇到问题:

  struct A {
int min_version;
int max_version;
std::vector<int> nodes;

A(std::vector<int> _nodes, int _min_version = 0, int _max_version = MAXINT)
: nodes(_nodes), min_version(_min_version), max_version(_max_version)
{};

};

static std::vector<A> a = list_of<A>
(list_of (1) (2))
;

我收到一个编译器错误,即 2 个重载都不能转换所有参数类型 (Visual Studio 2013)。但是,当我为一个或两个默认参数添加值时,它可以正常编译:

  static std::vector<A> a = list_of<A>
(list_of (1) (2), 1)
;

那么,让两个默认参数都起作用的诀窍是什么?

最佳答案

当您替换 list_of<A>(...) 时,单参数版本的问题变得更加明显通过 list_of(A(...)) : 编译器错误变成 (GCC):

list.cc: In function ‘int main()’:list.cc:18:30: error: call of overloaded ‘A(boost::assign_detail::generic_list<int>&)’ is ambiguous   list_of (A (list_of (1) (2)));                              ^list.cc:18:30: note: candidates are:list.cc:11:3: note: A::A(std::vector<int>, int, int)   A(std::vector<int> _nodes, int _min_version = 0, int _max_version = INT_MAX)   ^list.cc:6:8: note: A::A(const A&) struct A {        ^list.cc:6:8: note: A::A(A&&)

And this makes sense, sort of: the generic untyped list* claims to be convertible to any type; it does not (and probably cannot) use SFINAE to reject types to which the conversion wouldn't work.

In your example, a conversion from the untyped list to A is a better match than a conversion from the untyped list to std::vector<int> to A. That conversion, then, of course does not work.

When you pass the second argument, the compiler knows that you cannot possibly be attempting to call the copy constructor.

My personal preference would be to add a dummy argument to the constructor, similar to the standard's use of piecewise_construct_t:

struct from_vector { };
struct A {
...
A(std::vector<int> _nodes, ...) { ... }
A(from_vector, std::vector<int> _nodes, ...) : this(_nodes, ...) { }
};

然后你可以写

list_of<A>( from_vector(), list_of (1) (2) )

* 当我说“无类型列表”时,我当然意识到 Boost 实际上已经为该列表定义了一个类型,并且 C++ 表达式总是有一个类型。

关于c++ - 使用默认参数 boost list_of,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25402240/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com