C ++ Обнаружение функции перегрузки без конверсийC++

Программы на C++. Форум разработчиков
Ответить
Anonymous
 C ++ Обнаружение функции перегрузки без конверсий

Сообщение Anonymous »

У меня есть множество перегрузки функций, в основном состоящая из двух подписей: < /p>
void func(const my_type1&);
void func(const my_type2&, hash_t);
< /code>
и функция, которая пытается вызвать функцию на основе существования функции: < /p>
template
void func_imp(const T& t, hash_t hash){
if constexpr (has_func_with_2nd_param_v){
func(t, hash);
}else{
func(t);
}
}
< /code>
Но я сталкиваюсь с проблемами конверсии, которые в конечном итоге называют «неправильную» перегрузку: < /p>
#include
#include

struct hash_t{
};

struct my_type1{
my_type1() {}
};

struct my_type2{
my_type2() {}
my_type2(const my_type1&){}
};

void func(const my_type1&){
printf("no hash\n");
}

void func(const my_type2&, hash_t=hash_t()){
printf("hash\n");
}

template
struct has_func_with_2nd_param : std::false_type {};

template
struct has_func_with_2nd_param : std::true_type {};

template
constexpr bool has_func_with_2nd_param_v = has_func_with_2nd_param::value;

// I want to route to the appropriate function without conversion routing to the wrong func
template
void func_imp(const T& t, hash_t hash){
if constexpr (has_func_with_2nd_param_v){
func(t, hash);
}else{
func(t);
}
}

int main()
{
// this is true as expected
static_assert(has_func_with_2nd_param_v);

// this is also true, since my_type2 is constructable from my_type1 and then finds finds func(my_type2, hash_t)
static_assert(has_func_with_2nd_param_v);

func_imp(my_type1(), hash_t()); // prints "hash", but wanting it to call the "no hash" version
func_imp(my_type2(), hash_t()); // prints "hash"

return 0;
}
< /code>
У меня проблемы с придумыванием правильной мета -функции, чтобы получить поведение, которое я хочу. У кого -нибудь есть идеи?
Godbolt здесь

Подробнее здесь: https://stackoverflow.com/questions/795 ... onversions
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»