0

Currently using C++20, GCC 11.1.0.

I'm quite new to templates and concepts in general, but I wanted to create a template function with 1 to n number of arguments, constrained by the requirement of being able to be addition assigned += to a std::string. I've been searching for several days now but as you can see I am really struggling here.

Attempt 1:

template<typename T>
concept Stringable = requires (T t)
{
    {std::string += t} -> std::same_as<std::string::operator+=>;
};

template <typename Stringable ...Args>
void foo(Args&&... args)
{
    // Code...
}

EDIT: Attempt 2:

template<typename T>
concept Stringable = requires (std::string str, T t)
{
    str += t;
};

template <typename Stringable ...Args>
void foo(Args&&... args)
{
    // Code...
}

1 Answer 1

2

Attempt2 is pretty close, except that the typename keyword needs to be removed since Stringable is not a type but a concept. The correct syntax would be

#include <string>

template<typename T>
concept Stringable = requires (std::string str, T t) {
  str += t;
};

template<Stringable... Args>
void foo(Args&&... args) {
  // Code...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ohh it finally works now. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.