#include <vector>
#include <iostream>
#include <type_traits>
using namespace std;
template<typename Coll>
class has_push_back
{
using coll_type = decay_t<Coll>;
using True = char(&)[1];
using False = char(&)[2];
template<typename U, void(U::*)(const typename U::value_type&)>
struct SFINAE {};
template<typename T>
static True Test(SFINAE<T, &T::push_back>*);
template<typename T>
static False Test(...);
public:
enum { value = sizeof(Test<coll_type>(nullptr)) == sizeof(True) };
};
class MyColl : public vector<int> {};
int main()
{
cout << has_push_back<vector<int>>::value << endl;
cout << has_push_back<MyColl>::value << endl;
}
위의 프로그램은 다음을 출력합니다.
1
0
has_push_back
함수 push_back
가 상속 되면 템플릿 이 작동하지 않음을 보여줍니다 .
상속 되어도 작동하도록하는 방법이 있습니까?
완전성을 위해 이전에 언급하지 않은 다른 접근 방식을 게시하고 싶습니다.
이것은 함수의 정의와 별칭 선언을 기반으로합니다.
최소한의 작동 예제를 따릅니다.
#include <vector>
#include <type_traits>
#include<utility>
using namespace std;
template<typename T, typename... U>
constexpr auto f(int)
-> std::conditional_t<false, decltype(std::declval<T>().push_back(std::declval<U>()...)), std::true_type>;
template<typename, typename...>
constexpr std::false_type f(char);
template<typename T, typename... U>
using has_push_back = decltype(f<T, U...>(0));
class MyColl : public vector<int> {};
int main() {
static_assert(has_push_back<vector<int>, int>::value, "!");
static_assert(has_push_back<MyColl, int>::value, "!");
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다