Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Use std::is_base_of to subset STL container contents.
// C++11 #include <iostream> #include <type_traits> #include <vector> // Demonstrate use of template specialization and std::is_base_of to extract // subsets of STL containers based on the value_type of the output container. // Only items in the input container that can be cast or converted to the // output container type are appended. using namespace std; class A { public: virtual ~A() { }; }; class AA : public A { public: virtual ~AA() { }; int thing() const { return 42; } }; class AB : public A { public: virtual ~AB() { }; int thing() const { return 21; } }; class B { public: B() { m_thing = -1; } B(const AA* aa) { m_thing = aa ? aa->thing() : 0; } int thing() const { return m_thing; } protected: int m_thing; }; namespace internal { template< typename ContainerOut, typename ContainerIn, bool IsB > struct convertTo; template< typename ContainerOut, typename ContainerIn > struct convertTo<ContainerOut, ContainerIn, false> { static ContainerOut value(ContainerIn& container) { ContainerOut result; for (auto entry : container) { auto tmp = dynamic_cast<typename ContainerOut::value_type>(entry); if (tmp) { result.insert(result.end(), tmp); } } return result; }; }; template< typename ContainerOut, typename ContainerIn > struct convertTo<ContainerOut, ContainerIn, true> { static ContainerOut value(ContainerIn& container) { ContainerOut result; for (auto y : container) { AA* x = dynamic_cast<AA*>(y); if (x) { typename ContainerOut::value_type b(x); result.push_back(b); } } return result; } }; } // internal template< typename ContainerOut, typename ContainerIn > ContainerOut convertTo(ContainerIn& container) { return internal::convertTo< ContainerOut, ContainerIn, std::is_base_of<B, typename ContainerOut::value_type>::value >::value(container); } int main() { AA aa; AB ab; vector<A*> in{ &aa, &ab }; vector<B> out1; out1 = convertTo<std::vector<B>>(in); vector<AB*> out2; out2 = convertTo<std::vector<AB*>>(in); cout << "aa's thing: " << aa.thing() << "\n" << "ab's thing: " << ab.thing() << "\n" << "in size " << in.size() << "\n" << "out1 size " << out1.size() << "\n" << "out2 size " << out2.size() << "\n" << "out1 first thing: " << out1[0].thing() << "\n" << "out2 first thing: " << out2[0]->thing() << "\n"; return 0; }
run
|
edit
|
history
|
help
0
jkljklj
VS struct name enumerate
#7.2
hangman
Increment pointer to struct
Noexcept
Overload resolve function pointer
c++
MSVC_example_fscanf_s_and_chars_wchars
fusion adapt 64 members v2