Example
#include <string>
constexpr auto foo() {
return std::string{"bar"};
}
static_assert("bar" == foo());
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;}));
Solutions
[[nodiscard]] constexpr auto concat(auto... args) {
return ( ""s + ... + args() );
}
[[nodiscard]] constexpr auto concat(auto... args) {
std::string result{};
(result.append(args()), ...);
return result;
}
[[nodiscard]] constexpr auto concat(auto... args) {
return (args() + ... + std::string{});
}
[[nodiscard]] constexpr auto concat(auto... args){
if constexpr(sizeof...(args) > 0){
return std::string{(args() + ...)};
}
return std::string{};
}
[[nodiscard]] constexpr auto concat(auto... args) {
return (args() + ... + ""s);
}