【发布时间】:2019-02-21 10:04:26
【问题描述】:
我想使用性能。使用 initializer_list(大括号)转发,但我未能编写可编译的代码。
如何在下面的代码示例中进行类型推导?
#include <utility>
template <class _T> struct B {
_T a;
_T b; };
template <class _T> void bar(B<_T>&& a) {}
template <class _T> void bar(B<_T>& a) {}
template <class _T> struct A {
template <class __T>
void foo(__T&& a) {
bar(std::forward<__T>(a));
} };
int main() {
A<int> a;
a.foo({1, 3}); }
我知道可以使用可变参数模板参数进行完美转发,如下所示:
#include <utility>
template <class _T>
struct B {
_T a;
_T b;
};
template <class _T>
void bar(_T&& v1, _T&& v2) {
B<_T> b{v1, v2};
}
template <class _T>
void bar(_T& v1, _T& v2) {
B<_T> b{v1, v2};
}
template <class _T>
struct A {
template <class... Args>
void foo(Args&&... args) {
bar(std::forward<Args>(args)...);
}
};
int main() {
A<int> a;
a.foo(1, 3);
}
但我想用可爱的花括号打电话给foo。
【问题讨论】:
-
注意命名:保留包含
__的名称。见keyword。 -
我猜你做不到。编译器将无法将
{1, 3}推断为initializer_list。 -
... 就像
_T这样的名字。
标签: c++ initializer-list perfect-forwarding