也添加了 Boost Type Erasure 路由。
BOOST_TYPE_ERASURE_MEMBER((has_myFunction), myFunction, 0)
namespace bte = boost::type_erasure;
using Erased = bte::any<
boost::mpl::vector<
bte::copy_constructible<>,
has_myFunction<void(), bte::_self const>,
bte::relaxed
> >;
这有更多的学习曲线¹,但如果您有更多的概念需要满足,这可能是一个很好的权衡。
该示例还展示了如何实现映射值的值语义(假设 someTemplate<> 是可复制构造的)。
演示
Live On Coliru
#include <map>
#include <iostream>
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/member.hpp>
#include <boost/type_erasure/constructible.hpp>
BOOST_TYPE_ERASURE_MEMBER((has_myFunction), myFunction, 0)
namespace bte = boost::type_erasure;
using Erased = bte::any<
boost::mpl::vector<
bte::copy_constructible<>,
has_myFunction<void(), bte::_self const>,
bte::relaxed
> >;
template <typename T, typename U, typename V>
struct someTemplate {
void myFunction() const {
std::cout << __PRETTY_FUNCTION__ << "\n";
}
};
int main() {
std::map<int, Erased> assocArr {
{ 1, someTemplate<int, int, char> {} },
{ 2, someTemplate<char, int, char> {} },
{ 3, someTemplate<double, double, int> {} },
{ 4, someTemplate<int, int, char> {} },
{ 5, someTemplate<int, int, float> {} },
};
for(auto& item : assocArr)
//if(item.first == integerVar)
{
std::cout << "id: " << item.first << " ";
item.second.myFunction();
}
}
印刷:
id: 1 void someTemplate<T, U, V>::myFunction() const [with T = int; U = int; V = char]
id: 2 void someTemplate<T, U, V>::myFunction() const [with T = char; U = int; V = char]
id: 3 void someTemplate<T, U, V>::myFunction() const [with T = double; U = double; V = int]
id: 4 void someTemplate<T, U, V>::myFunction() const [with T = int; U = int; V = char]
id: 5 void someTemplate<T, U, V>::myFunction() const [with T = int; U = int; V = float]
¹正如现场直播所证明的那样:)