Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compile time string concatenation using constexpr

Tags:

c++

string

#include <iostream>
#include <string>

constexpr std::string appendStringC(std::string s)
{
    return s + " Constexpr func";
}

std::string appendString(std::string s)
{
    return s + " Regular func";
}

int main()
{
    std::string s1 = "String 1";
    std::string s2 = "String 2";
    std::cout << std::endl
              << appendStringC(s1) << std::endl
              << appendString(s2) << std::endl;
    return 0;
}

I'm trying to perform compile time string prefix/postfix concatenation operation using constexpr. However this example is producing following errors:

const_string_generation.cpp: In function ‘constexpr std::__cxx11::string appendStringC(std::__cxx11::string)’:
const_string_generation.cpp:4:23: error: invalid type for parameter 1 of constexpr function ‘constexpr std::__cxx11::string appendStringC(std::__cxx11::string)’
 constexpr std::string appendStringC(std::string s)
                       ^
In file included from /usr/include/c++/5.3.0/string:52:0,
                 from /usr/include/c++/5.3.0/bits/locale_classes.h:40,
                 from /usr/include/c++/5.3.0/bits/ios_base.h:41,
                 from /usr/include/c++/5.3.0/ios:42,
                 from /usr/include/c++/5.3.0/ostream:38,
                 from /usr/include/c++/5.3.0/iostream:39,
                 from const_string_generation.cpp:1:
/usr/include/c++/5.3.0/bits/basic_string.h:71:11: note: ‘std::__cxx11::basic_string<char>’ is not literal because:
     class basic_string
           ^
/usr/include/c++/5.3.0/bits/basic_string.h:71:11: note:   ‘std::__cxx11::basic_string<char>’ has a non-trivial destructor
const_string_generation.cpp:4:23: error: invalid return type ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ of constexpr function ‘constexpr std::__cxx11::string appendStringC(std::__cxx11::string)’
 constexpr std::string appendStringC(std::string s)

since std::string isn't a literal. I'm looking for an easy way to do this and I don't care about backward compatiblity for this very example. Ideone : Link


like image 322
Abhinav Gauniyal Avatar asked Jan 04 '16 11:01

Abhinav Gauniyal


1 Answers

std:string::operator+() isn't a constexpr, in fact it's usually implemented in a very dynamic manner that relies on heap memory. You can append static string constants like this:

"append this string " " to this string"
like image 62
Paul Evans Avatar answered Oct 31 '22 12:10

Paul Evans