C++ constexpr function parameters

Viewed 43

With this nice simplified compile time string class.

There are no constexpr/consteval function parameters in C++ but the point of this question is:

Can I get a function call style for passing of non-type template parameters ? With the suffix I can get pretty close. But can it be done better ?

I do not want to use this syntax

test_normal_function2<"asd">(x);

How can I get rid of _fs suffix in the invocation of test_normal_function ?

#include <algorithm>

struct no_init_fixed_string {};

template <std::size_t N>
struct fixed_string 
{
    constexpr fixed_string(const char (&foo)[N + 1]) 
    {
        std::copy_n(foo, N + 1, data.begin());
    }
    
    std::array<char, N + 1> data{};

    constexpr fixed_string(no_init_fixed_string) 
        : data{} 
    {
    }
};


template <std::size_t N>
fixed_string(const char (&str)[N]) -> fixed_string<N - 1>;


template<fixed_string s>
struct fixed_string_type
{
};

template<fixed_string s>
constexpr auto operator"" _fs()
{
    return fixed_string_type<s>{};
}


template<fixed_string s>
void test_normal_function(fixed_string_type<s>, int x )
{
    //use s as consexpr parameter
}

template<fixed_string s>
void test_normal_function2( int x )
{

}

int main()
{
    int x = 3;
    test_normal_function("asd"_fs,x);  //this works
    test_normal_function2<"asd">(x); // this works but its ugly
    //test_normal_function("asd",x);  //this doesn't compile but its pretty.
}

How can I make call to test_normal_function work without _fs suffix ?

1 Answers

Preprocessor macro trickery aside, it is impossible to do it with the exact syntax you want, because a usual string literal (not a user-defined literal) does never encode its value in its type (only its length).

A value passed to a function via a function parameter can never be used by the function in a constant expression. Only information in the type can be used that way.

However, you can pass a value via a template parameter and make use of it in a constant expression:

test_normal_function<"asd">({},x);
Related