【发布时间】:2016-05-17 07:40:56
【问题描述】:
以下内容在 Visual C++ 2015 Update 2 上运行良好。请注意,A 是不可复制的,A::A 是 explicit。
#include <iostream>
#include <tuple>
struct A
{
explicit A(int i)
{
std::cout << i << " ";
}
// non-copyable
A(const A&) = delete;
A& operator=(const A&) = delete;
};
template <class... Ts>
struct B
{
std::tuple<Ts...> ts;
B(int i)
: ts((sizeof(Ts), i)...)
{
}
};
int main()
{
B<A, A, A, A> b(42);
}
目标是将相同的参数传递给所有元组元素。它正确输出:
42 42 42 42
但是,它无法在 g++ 4.9.2 上编译。在众多消息中,我认为应该调用 tuple 构造函数重载:
In instantiation of ‘B<Ts>::B(int) [with Ts = {A, A, A, A}]’:
33:24: required from here
25:30: error: no matching function for call to
‘std::tuple<A, A, A, A>::tuple(int&, int&, int&, int&)’
: ts((sizeof(Ts), i)...)
[...]
/usr/include/c++/4.9/tuple:406:19: note: template<class ... _UElements, class>
constexpr std::tuple< <template-parameter-1-1> >::tuple(_UElements&& ...)
constexpr tuple(_UElements&&... __elements)
^
/usr/include/c++/4.9/tuple:406:19: note: template argument deduction/substitution failed:
/usr/include/c++/4.9/tuple:402:40: error: no type named ‘type’ in
‘struct std::enable_if<false, void>’
template<typename... _UElements, typename = typename
消息中的函数签名不完整,但是引用了这个:
template<typename... _UElements, typename = typename
enable_if<__and_<is_convertible<_UElements,
_Elements>...>::value>::type>
explicit constexpr tuple(_UElements&&... _elements)
: _Inherited(std::forward<_UElements>(__elements)...) { }
我的理解是 is_convertible 对于显式构造函数失败。 g++ 5.1 和 clang 3.5 有类似的错误信息。
现在,在 C++14 中,20.4.2.1/10 说:“除非UTypes 中的每个类型都可以隐式转换为Types 中的相应类型,否则此构造函数不应参与重载决议”。这给我的印象是 g++ 和 clang 实际上有这个权利,而 Visual C++ 过于宽容。
[编辑:似乎 C++17 已经删除了这个限制,Visual C++ 2015 也遵循了它。它现在说:“此构造函数不应参与重载决议,除非 [...] is_constructible<Ti, Ui&&>::value 对于所有 i 都是 true。”看起来“可隐式转换”已更改为“is_constructible”。但是,我仍然需要 C++14 解决方案。]
我尝试从构造函数中删除explicit(我更愿意保留它)。 Visual C++ 再次编译正常,但 g++ 和 clang 都抱怨删除的复制构造函数。因为int 现在可以隐式转换为A,所以我似乎最终进入了
explicit constexpr tuple(const Types&...)
这会将ints 隐式转换为一堆As,然后尝试复制它们。我实际上不确定我将如何使用其他构造函数。
在 C++14 中,如果构造函数是 explicit,我如何让 tuple 通过将相同的参数传递给每个构造函数来初始化其元素?
【问题讨论】:
-
这接近于this one,但解决方案似乎不适用于
explicit构造函数。 -
似乎是 libstdc++ 中的一个错误,适用于 libc++ Demo without explicit 和 with
-
@Jarod42 我对 20.4.2.1/1 的解读是 libstdc++ 实际上是正确的,不是吗?
-
我阅读了非官方的tuple constructor 并且要求很有意义。
!is_convertible部分将是explicit用于tuple。 -
sizeof返回std::size_t,一个无符号类型,但您接受一个有符号类型int作为参数。
标签: c++ constructor tuples variadic-templates explicit