我正在嘗試根據傳入的序列容器是否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
uj5u.com熱心網友回復:
您可以為此使用運算式 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
&T::push_backpush_back模板或多載時可能格式不正確。t.front()相反,我檢查與to的呼叫push_back是否有效。當然這也要求型別有合適的front成員。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/433963.html
下一篇:部分模板專業化錯誤
