我定义了很多模板类变量,如下所示:
someTemplate<int, int, char> variable1;
someTemplate<char, int, char> variable2;
someTemplate<double, double, int> variable3;
someTemplate<int, int, char> variable4;
someTemplate<int, int, float> variable15;
...
现在,我想定义关联 std::map,但我不知道如何编写类型签名(声明)...如果可能的话。例如:
std::map<int,_____> assocArr;
我需要它,因为我想使用循环调用 std::map 的所有项目上的函数:
for(auto item : assocArr)
{
if(item.first == integerVar)
item.second->myFunction();
}
我知道,这个简单的解决方案是 make class,它封装了所有模板类,但我的问题是是否可以在没有此类的情况下做到这一点? 由于模板类有许多变体,所以 boost::variant 的使用是有问题的。
最佳答案
还添加了 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
> >;
这需要更多的学习曲线,但如果您有更多概念需要满足,这可能是一个非常好的权衡。
该示例还展示了如何实现 map 值的值语义(假设 someTemplate<>
是可复制构造的)。
演示
#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]
1 正如现场直播所证明的那样:)
关于c++ - 模板类的 std::map 类型签名(声明),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33017439/