简体   繁体   中英

Can I create constexpr strings with functions?

I have a method that creates a file header with a given comment symbol , depending on the output file type. There are only a few supported file types, thus I want to create these headers at compile time. Can I make these as a constexpr ?

std::string create_header(const std::string &comment_symbol) {
    std::string div(15, '-');
    std::string space(2, ' ');

    std::stringstream hdr;
    hdr << comment_symbol << space << " Begin of File." << std::endl;
    hdr << comment_symbol << space << div << std::endl;
    return hdr.str();
}

std::string c_header() { return create_header("//"); }
std::string python_header() { return create_header("#"); 

Can I create constexpr strings with functions?

You can't return std::string , cause it allocates memory.

Can I make these as a constexpr ?

Sure, something along:

#include <array>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>

template<size_t N> constexpr
auto create_header(const char (&comment_symbol)[N]) {
  const char one[] = "  Begin of File.\n";
  const char two[] = " -\n";
  std::array<char,
    N + (sizeof(one) - 1) +
    N + (sizeof(two) - 1) + 1
  > ret{};
  auto it = ret.begin();
  for (const char *i = comment_symbol; *i; ++i) *it++ = *i;
  for (const char *i = one; *i; ++i) *it++ = *i;
  for (const char *i = comment_symbol; *i; ++i) *it++ = *i;
  for (const char *i = two; *i; ++i) *it++ = *i;
  return ret;
}


std::string c_header() {
    constexpr auto a = create_header("//");
    return std::string{a.begin(), a.end()};
}

int main() {
    std::cout << c_header() << '\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM