Skip to content

Latest commit

 

History

History
81 lines (58 loc) · 1.65 KB

279.md

File metadata and controls

81 lines (58 loc) · 1.65 KB
Info

Example

#include <string>

constexpr auto foo() {
  return std::string{"bar"};
}

static_assert("bar" == foo());

https://godbolt.org/z/P9qW6jYav

Puzzle

  • Can you implement concat which concatenates given strings?
[[nodiscard]] constexpr auto concat(auto... args); // TODO

static_assert(""s == concat());
static_assert("a"s == concat([]{return "a"s;}));
static_assert("ab"s == concat([]{return "a"s;}, []{return "b"s;}));
static_assert("abc"s == concat([]{return "a"s;}, []{return "b"s;}, []{return "c"s;}));

https://godbolt.org/z/6MaMqrKzE

Solutions

[[nodiscard]] constexpr auto concat(auto... args) {
    return ( ""s + ... + args() );
}

https://cpp_tip_of_the_week.godbolt.org/z/3f7fh4Yd5

[[nodiscard]] constexpr auto concat(auto... args) {
    std::string result{};
    (result.append(args()), ...);
    return result;
}

https://godbolt.org/z/xh8oancaf

[[nodiscard]] constexpr auto concat(auto... args) {
  return (args() + ... + std::string{});
}

https://godbolt.org/z/rjPz7qnn8

[[nodiscard]] constexpr auto concat(auto... args){
    if constexpr(sizeof...(args) > 0){
        return std::string{(args() + ...)};
    }
    return std::string{};
}

https://godbolt.org/z/c4eojWhTs

[[nodiscard]] constexpr auto concat(auto... args) {
    return (args() + ... + ""s);
}

https://godbolt.org/z/TeEcEWcra