C++如何通过标签
问题描述:
还有很多的模板函数称为F1,F2,F3 ......C++如何通过标签
如何分派运行知名INT到不同的模板功能,分派到不同的模板功能?
当然,我可以使用开关来做到这一点,但每次添加更多的模板功能或删除一些模板功能时,我必须一次又一次地修改开关。我怎样才能以更优雅的方式做到这一点?
模板不是真正的函数,所以我不能创建函数指针的std :: map。
template<typename T> std::optional<T> f1(){...}
template<typename T> std::optional<T> f2(){...}
template<typename T> std::optional<T> f3(){...}
template<typename T> std::optional<T> f4(){...}
template<typename T> auto dispatch(int tag){
switch(i){
case 1: return f1<T>();
case 2: return f2<T>();
case 3: return f3<T>();
case 4: return f4<T>();
}// I have to modify these if add or delete some template functions
}
答
以下是对command pattern的解释,我想它是你在找什么。
没有模板化函数,所以我重写了它。它没有做它的目的(转换数字),但你可以选择你想调用的函数和它的模板。
#include <iostream>
#include <string>
#include <bitset>
#include <sstream>
#include <map>
#include <cctype>
template <typename T>
class converter
{
public:
virtual std::string convert(T) = 0;
virtual ~converter() {}
};
template <typename T>
class hex_converter : public converter<T>
{
public:
std::string convert(T i)
{
return "H: " + i;
}
};
template <typename T>
class oct_converter : public converter<T>
{
public:
std::string convert(T i)
{
return "O: " + i;
}
};
template <typename T>
class bin_converter : public converter<T>
{
public:
std::string convert(T i)
{
return "B: " + i;
}
};
class dictionary
{
std::map<char, converter<std::string>*> dict;
public:
dictionary()
{
dict.insert(std::make_pair('B', new bin_converter<std::string>));
dict.insert(std::make_pair('O', new oct_converter<std::string>));
dict.insert(std::make_pair('H', new hex_converter<std::string>));
}
converter<std::string>* lookup(char x)
{
std::map<char, converter<std::string>*>::const_iterator iter;
iter = dict.find(toupper(x));
if(iter != dict.end())
return iter->second;
else
return NULL;
}
~dictionary()
{
while(dict.begin() != dict.end())
{
delete dict.begin()->second;
dict.erase(dict.begin());
}
}
};
int main()
{
using namespace std;
char ch = 'h';
string output = "";
dictionary dict;
converter<std::string>* con = dict.lookup(ch);
if(con != NULL)
output = con->convert("Test");
else
output = "Invalid";
cout << "Result: " << output;
}
+0
不是我一直在寻找的anwser。你派遣字符到函数(尽管从模板初始化),我想分配int到不同的模板。模板不是现成的函数,所以我不能创建函数指针的std :: map。我想要的是有点像double-dispatch,但是通过int和模板的类型参数调度。我可以通过切换来实现,但是当我经常添加或删除模板时,它不适合这种情况,因为我必须添加或删除相应的切换器。 –
请显示一些代码 – user463035818