以下内容在 Visual C++ 2015 Update 2 上运行良好。请注意A
是不可复制的并且A::A
is 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
is true
对全部i
” 看起来“可隐式转换”改为“is_constructible
”。但是,我仍然需要一个 C++14 解决方案。]
我尝试删除explicit
来自构造函数(我更愿意保留它)。 Visual C++ 再次编译良好,但 g++ 和 clang 都抱怨删除的复制构造函数。因为int
现在可以隐式转换为A
,我似乎最终陷入
explicit constexpr tuple(const Types&...)
这会隐式转换int
变成一堆A
s,然后尝试复制它们。我实际上不确定如何使用其他构造函数。
在C++14中,我怎样才能得到tuple
如果构造函数是,则通过将相同的参数传递给每个构造函数来初始化其元素explicit
?