1

I want to be able to pass a string literal to a class instance and also check at compile time for certain conditions on the string literal. But I want the string checking to be done by the class somehow. I have a sample code with roughly what I'm trying to achieve:

#include <type_traits>
#include <string>
#include <string_view>

class TestString
{
public:

    constexpr bool TestStringCondition(const char* name) noexcept
    {
        return std::string_view(name).find('a') != std::string_view::npos; //random condition
    }

    constexpr TestString(const char* name) noexcept:
        m_name(name)
    {
        static_assert(TestStringCondition(name), "error message");
    }

    const char* m_name = nullptr;
};

int main()
{
    static constexpr const char* const name = {"foo"};

    static const TestString testString { name };
}

I tried various options (templates, char_traits, etc.) but keep getting compiler error "static_assert expression is not an integral constant expression". It seems to not be happy with the stringliteral passed as a parameter as I can do the assert check outside the class. I cannot use any c++20 features yet and I want a way avoiding Boost. Does anyone know a way?

domoremath
  • 555
  • 2
  • 8
  • 17

1 Answers1

0

The following works but I am unsure if it is what you want:

#include <type_traits>
#include <string_view>

template<const char *const t_name>
class TestString {
  public:
    static constexpr bool TestStringCondition(const char *name) noexcept {
        return std::string_view(name).find('a') != std::string_view::npos;  // random condition
    }

    constexpr TestString() noexcept {
        static_assert(TestStringCondition(t_name));
    }
};

constexpr char okay[] = "okay";  // array, so it is a static object with linkage
int main() {
    static const TestString<okay> testString{};
}
n314159
  • 4,990
  • 1
  • 5
  • 20
  • Thanks. I would prefer for TestString to not be a template but I don't know if that is possible. – domoremath Feb 06 '21 at 08:24
  • It is not possible. Even for constexpr functions (or also consteval), functions arguments are not usable in constant expressions (https://stackoverflow.com/questions/57226797/will-consteval-allow-using-static-assert-on-function-arguments). Btw, the static_assert can be moved in the body of the class. That makes no difference. – n314159 Feb 06 '21 at 13:20