Debian Codegraph @

gcc/testsuite/g++.dg/cpp26/constexpr-voidptr1.C

raw
1 // PR c++/110344
2 // { dg-do compile { target c++26 } }
3 // { dg-skip-if "requires hosted libstdc++ for cwchar" { ! hostedlib } }
4
5 #include <string_view>
6 struct Sheep {
7 constexpr std::string_view speak() const noexcept { return "Baaaaaa"; }
8 };
9 struct Cow {
10 constexpr std::string_view speak() const noexcept { return "Mooo"; }
11 };
12 class Animal_View {
13 private:
14 const void *animal;
15 std::string_view (*speak_function)(const void *);
16 public:
17 template <typename Animal>
18 constexpr Animal_View(const Animal &a)
19 : animal{&a}, speak_function{[](const void *object) {
20 return static_cast<const Animal *>(object)->speak();
21 }} {}
22 constexpr std::string_view speak() const noexcept {
23 return speak_function(animal);
24 }
25 };
26 // This is the key bit here. This is a single concrete function
27 // that can take anything that happens to have the "Animal_View"
28 // interface
29 constexpr std::string_view do_speak(Animal_View av) { return av.speak(); }
30 int main() {
31 // A Cow is a cow. The only think that makes it special
32 // is that it has a "std::string_view speak() const" member
33 constexpr Cow cow;
34 constexpr auto result = do_speak(cow);
35 return static_cast<int>(result.size());
36 }