一个用来ghs的、使用了concept、折叠表达式、模板形参包做基类列表等技巧的模板元编程Mixin Demo

昨天看Mixin时突发奇想,写着玩的。图一乐。

直接上代码,受限于平台,Show()部分自行脑补。

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <concepts>
#include <iostream>

template<typename T>
concept IsSexuality = requires{ T::Show(); };

template<IsSexuality... Sexuality>
struct GirlFriend :private Sexuality...
{
constexpr GirlFriend() :Sexuality()... {}
constexpr void ShowSexuality() const
{
std::cout << "I have a girl friend.\n";
if constexpr (sizeof...(Sexuality) > 0)
{
std::cout << "She can:\n";
((Sexuality::Show()), ...);
} else
{ std::cout << "She was a virgin.\n"; }
}
};
struct MakeLoveable
{ static void Show() { std::cout << "Make love with me.\n"; } };
struct BlowJobable
{ static void Show() { std::cout << "BlowJob.\n"; } };
struct FootJobable
{ static void Show() { std::cout << "FootJob.\n"; } };
//...

template<typename T>
concept IsSexSkill = IsSexuality<T> && !std::same_as<T, MakeLoveable>;

template<IsSexSkill... SexSkills>
using ReallyGirlFriend = GirlFriend<MakeLoveable, SexSkills...>;

int main()
{
constexpr GirlFriend girlFriend;
constexpr ReallyGirlFriend<> reallyGirlFriend;
constexpr ReallyGirlFriend<BlowJobable, FootJobable> sexyGirlFriend;
girlFriend.ShowSexuality();
reallyGirlFriend.ShowSexuality();
sexyGirlFriend.ShowSexuality();
}

//output:
/*------------------------
I have a girl friend.
She was a virgin.
I have a girl friend.
She can:
Make love with me.
I have a girl friend.
She can:
Make love with me.
BlowJob.
FootJob.
------------------------*/

原文链接: https://zhuanlan.zhihu.com/p/460970247