简体   繁体   中英

C++ Constrained Variadic Template Parameters

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...
}

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM