输入具有特定成员函数的重载函数
我试图根据传入的序列容器是否将 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
I'm attempting to overload a function depending on whether the passed in sequence container has push_back
as a member function.
#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;
}
This results in the following compiler error for each of the calls to 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'
Expected result:
Has push_back
No push_back
No push_back
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 表达式 SFINAE 来实现:
结果:
https://godbolt.org/z/dbzafs1nY
当
push_back
是模板或重载时,&T::push_back
的格式可能不正确。相反,我检查使用t.front()
对push_back
的调用是否有效。当然,这也要求类型有合适的front
成员。You could use expression SFINAE for this:
Result:
https://godbolt.org/z/dbzafs1nY
&T::push_back
may not be well formed whenpush_back
is a template or overloaded. Instead, I check if a call witht.front()
topush_back
is valid or not. Of course this also requires the type to have a suitablefront
member.