Как создать простой concept на ограничение типов по списку?
Попытался написать свой первый концепт и застрял на непонятной для меня ошибке.
Вот код:
#include <type_traits>
#include <string>
template<typename Type>
concept String = std::is_same_v<Type,const char*>
|| std::is_same_v<Type,std::string>;
template<String Type>
void function(Type&& string)
{
std::forward<Type>(string);
}
int main()
{
std::string string{"7"};
function(string);
return 0;
}
Вот вывод:
error: use of function 'void function(Type) [with Type = std::__cxx11::basic_string]' with unsatisfied constraints
Я прочитал про requires, но не понимаю, как его применить в данном случае?
Ответы (1 шт):
Автор решения: megorit
→ Ссылка
Итак, получилось вот так:
#include <string>
#include <concepts>
#include <type_traits>
template<typename Type>
concept String = std::same_as<std::remove_cvref<Type>,std::string>;
template<String Type>
void function(Type&& string)
{
std::forward<Type>(string);
}
int main()
{
std::string string1{"7"};
const std::string string2{"7"};
function(string1);
function(string2);
function(std::string{"7"});
return 0;
}
Правда, все равно, по-хорошему придется для const char* делать специализацию.