输入具有特定成员函数的重载函数

Overloading function where input has certain member function

我正在尝试根据传入的序列容器是否具有 push_back 作为成员函数来重载函数。

#include <vector>
#include <forward_list>
#include <list>
#include <array>
#include <iostream>

template<class T, typename std::enable_if_t<std::is_member_function_pointer_v<decltype(&T::push_back)>, int> = 0>
void has_push_back(T p)
{
  std::cout << "Has push_back" << std::endl;
}

template<class T, typename std::enable_if_t<!std::is_member_function_pointer_v<decltype(&T::push_back)>, int> = 0>
void has_push_back(T p)
{
  std::cout << "No push_back" << std::endl;
}

int main() {
  std::vector<int> vec = { 0 };
  std::array<int, 1> arr = { 0 };
  std::forward_list<int> f_list = { 0 };

  has_push_back(vec);
  has_push_back(arr);
  has_push_back(f_list);
  
  return 0;
}

这会导致每次调用 has_push_back() 时出现以下编译器错误:

error C2672: 'has_push_back': no matching overloaded function found
error C2783: 'void has_push_back(T)': could not deduce template argument for '__formal'

预期结果:

Has push_back
No push_back
No push_back

您可以为此使用 expression SFINAE

#include <iostream>
#include <vector>
#include <array>
#include <forward_list>

void has_push_back(...)
{
  std::cout << "No push_back" << std::endl;
}

template<class T>
auto has_push_back(T&& t) 
  -> decltype(t.push_back(t.front()), void()) 
  // ^^ expression SFINAE, only considered 
  // if the whole expression within decltype is valid
{
  std::cout << "Has push_back" << std::endl;
}

int main() {
  std::vector<int> vec = { 0 };
  std::array<int, 1> arr = { 0 };
  std::forward_list<int> f_list = { 0 };

  has_push_back(vec);
  has_push_back(arr);
  has_push_back(f_list);
  
  return 0;
}

结果:

Has push_back
No push_back
No push_back

https://godbolt.org/z/dbzafs1nY

push_back 是模板或重载时,

&T::push_back 可能格式不正确。相反,我检查 t.front()push_back 的调用是否有效。当然这也需要类型有合适的front成员。