4

I'd like to determine if a string contains a particular character at compile time. I thought I would use std::string_view as it has constexpr methods to do what I want. This is the code:

#include <iostream>
#include <string_view>

using namespace std::literals;

template<std::size_t N>
constexpr bool ContainsAsterisk(const char(&formatString)[N])
{
    constexpr std::string_view fmtString{ formatString, N - 1 }; // error C2131: expression did not evaluate to a constant
    constexpr bool containsAsterisk = fmtString.find('*') != fmtString.npos;
    return containsAsterisk;
}


int main()
{
    if (ContainsAsterisk("sdf"))
    {
        std::cout << "sdf no\n";
    }

    if (ContainsAsterisk("er*r"))
    {
        std::cout << "er*r yes\n";
    }


    std::cout << "done\n";
}

This doesn't compile because of these errors

ConsoleApplication.cpp(9,41): error C2131: expression did not evaluate to a constant
ConsoleApplication.cpp(9,43): message : failure was caused by a read of a variable outside its lifetime
ConsoleApplication.cpp(9,43): message : see usage of 'formatString'
ConsoleApplication.cpp(17): message : see reference to function template instantiation 'bool ContainsAsterisk<4>(const char (&)[4])' being compiled
ConsoleApplication.cpp(10,37): error C2131: expression did not evaluate to a constant
ConsoleApplication.cpp(9,43): message : failure was caused by a read of a variable outside its lifetime
ConsoleApplication.cpp(9,43): message : see usage of 'formatString'

I've done quite a bit of googling, and can't understand what this error is telling me! I don't understand how the variable is being read outside it's lifetime, it's a literal (isn't it?) that I thought would be available at compile time.

Any tips explaining the error and how to fix would be appreciated. Thanks.

7
  • Do you have to use string_view and find? Can you not simply just loop over formatString?
    – Tas
    Nov 25, 2020 at 21:26
  • A function parameter, even in constexpr functions is never a compile time constant. Is there a reason you don't just accept a std::string_view as the function parameter? Nov 25, 2020 at 21:32
  • I tried accepting std::string_view as the function parameter and got a similar error Nov 25, 2020 at 21:34
  • I don't have to use string_view, but was curios why it didn't work. I may have a go at using a loop. Nov 25, 2020 at 21:35
  • 1
    With my eyes, yes! But, this is used within a macro for log statements. There are thousands of them. I want the compiler to do the work don't want to end up needing to pass in an an error prone additional parameter to say if there is or isn't an asterisk. Nov 25, 2020 at 21:41

3 Answers 3

3

You are overcomplicating things. std::string_view can be constructed by const char*:

constexpr bool ContainsAsterisk(std::string_view view) {
    // constexpr bool b = view.find('*') != view.npos; // ERROR
    return view.find('*') != view.npos;
}

int main() {
  constexpr bool b = ContainsAsterisk("123123*"); // OK
}

Why am I getting the error?

According to cppreference, a function can be constexpr if:

there exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a core constant expression [...]

This means that it's not necessary for a constexpr function to always return a constexpr value, neither is it expected to always receive a constexpr argument. It only makes sure that for some specific set of arguments (a constexpr const char* in thie case), it will give a constexpr return value.

Therefore, a definition that assumes the argument is always constexpr (see ERROR line above) is invalid.

6
  • Hmm, yes, seems that defining the interim result gets me back to the same error. I hadn't realized that. I'm still not sure why it does result in the error. ``` constexpr bool ContainsAsterisk(std::string_view view) { constexpr bool contains = view.find('*') != view.npos; return contains; } ``` Nov 25, 2020 at 21:39
  • @ScottLangham Function paramters are never constexpr. That means you can't initialize a constexpr variable using the function parameter. Nov 25, 2020 at 21:47
  • @NathanOliver I believe that's incorrect. Arguments can be constexpr, they just cannot be declared to necessarily be constexpr. This is what a template parameter is for.
    – Kostas
    Nov 25, 2020 at 21:50
  • @Kostas A template parameter is not a function parameter. You can see my answer for more. Nov 25, 2020 at 21:51
  • Ok, your last sentence helps. I'd been incorrectly assuming that I could write the function such that it would compile successfully if called with suitable constexpr arguments, and I wouldn't have to care about it being called with non constexpr arguments as I never intend to do that. But, attempting to apply my knowledge of how templates work to constexpr functions is the wrong thing to do! Nov 25, 2020 at 22:08
1

Your code can simply be written as:

template<std::size_t N>
constexpr bool ContainsAsterisk(const char(&formatString)[N])
{
    for (auto c : formatString)
    {
        if (c == '*')
        {
            return true;
        }
    }
    return false;
}

You don't actually need to use string_view.

Unfortunately I can't explain to you why string_view doesn't work.

1

You already have answers on how else to do this so I wont add anything more to that but this answer will address

I don't understand how the variable is being read outside it's lifetime, it's a literal (isn't it?) that I thought would be available at compile time.

Yes, a string literal is a compile time constant. The issue here is that a function parameter is not a compile time constant, even if it is initialized from one. To see why that is, lets start with the function

template <auto var>
auto foo()
{
    if constexpr (var == 1)
        return 1;
    else
        return 1.0;
}

This function template will have two different return types, but only one of them will ever be used in a specialization so you still follow the rule of one return type per function. Now if we allowed constexpr function parameters like

auto foo(constexpr int var)
{
    if constexpr (var == 1)
        return 1;
    else
        return 1.0;
}

This function will either return a int or a double, but you can't have one function that has different return types.

3
  • Thanks. I'll take your word for it that a function parameter can't be a compile time constant. In my head this seems to be telling me that @Kostas answer shouldn't work at compile time, but it does. I'm ending up more confused :) Nov 25, 2020 at 21:56
  • Also, sorry, but I don't really understand your example. What if you defined the second foo to return 1 or return 2. That avoids the different return types issue, but I don't see the relation between the example and whether or not the parameter is a compile time constant or not. I guess this is clear in your head and you must be two steps ahead of me cuz I'm missing the middle step. I'm new to the world of constexpr, obviously I have much to learn. Nov 25, 2020 at 21:58
  • I like the his example. It shows the motivation behind this design choice.
    – Kostas
    Nov 25, 2020 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.