C ++ SFINAE Resolution Order

I have two functions

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

template <typename... Args>
void foo(const std::string& name, Args&&... args) { /* ... */ }

Currently, all calls, such as foo("bar", /* arguments */), are trying to switch to the first function instead of the second. I want to reorder these functions so that SFINAE finds second place before first. I cannot use std::enable_ifchar array / string to check the array, because the package Args...may contain std::string&or const char (&) []. How to do it?

+4
source share
2 answers

, "bar" std::string. void foo(const std::string& name, Args&&... args), , void foo(Args&&... args) .

string operator "bar" "bar"s.

template <typename... Args>
void foo(const std::string& name, Args&&... args) { /* ... */ }

template <typename... Args>
void foo(std::string&& name, Args&&... args) { /* ... */ }

template <typename... Args>
void foo(std::string& name, Args&&... args) { /* ... */ }

as "bar"s prvalue , rvalue, const lvalue.

+6
template <typename... Args>
void foo(Args&&... args) { /* ... */ }

, , , , . , , - - - , .

- SFINAE, , std::string, std::is_convertible.

// General case
template <typename First, typename... Rest,
          std::enable_if_t<!std::is_convertible<First, std::string>::value, int> = 0>
void foo(First&& first, Rest&&... rest) { ... }

// First argument can be converted to string
template <typename... Args>
void foo(const std::string& first, Args&&... args) { ... }

Corilu

+6

Source: https://habr.com/ru/post/1683026/


All Articles