Perfect Forwarding And Piecewise Construct
Perfect Forwarding And Piecewise Construct
简介
完美转发与分段构造用例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <map>
#include <functional>
#include <typeinfo>
#include <typeindex>
#include <iostream>
class MyClass
{
public:
int a;
int b;
MyClass(int a, int b) : a(a), b(b) {}
};
std::map<std::type_index, MyClass> myMap;
template<class T, typename... Args>
T &Test(Args&&... args)
{
auto it = myMap.emplace(std::forward<Args>(args)...);
return it.first->second;
}
int main()
{
// g++ 4.8+
auto ref = Test<MyClass>(
std::piecewise_construct,
std::forward_as_tuple<std::type_index>(typeid(MyClass)),
std::forward_as_tuple<int, int>(10, 100)
);
std::cout<<ref.a<<", "<<ref.b<<std::endl;
return 0;
}
参考
This post is licensed under CC BY 4.0 by the author.