用于区分对象类型的模板类? 我可以使用C++模板类来区分对象类型吗?或者我应该用什么
例如,我有一个类用于区分对象类型的模板类? 我可以使用C++模板类来区分对象类型吗?或者我应该用什么,c++,templates,polymorphism,C++,Templates,Polymorphism,例如,我有一个类同义词,它可以是语句、过程等类型。我有一些函数可以接受这些同义词,并根据其类型对其求值。所以我在想,如果我能做一些事情,比如: enum Types { Statement, Procedure, Variable, ... }; template <typename Types> class Synonym { ... } void evaluate(Synonym<Statement> s, Synonym<Variable> v) {
同义词
,它可以是语句、过程等类型。我有一些函数可以接受这些同义词,并根据其类型对其求值。所以我在想,如果我能做一些事情,比如:
enum Types { Statement, Procedure, Variable, ... };
template <typename Types>
class Synonym { ... }
void evaluate(Synonym<Statement> s, Synonym<Variable> v) { do something }
^ so that I can do this ... instead of checking the type in function like:
void evaluate(Synonym s, Synonym v) {
assert(s.type == Statement);
assert(v.type == Variable);
// also would like to eliminate things like: (if possible)
switch(s.type) {
case XXX: doSomething ...
case YYY: doAnotherThing ...
}
}
enum类型{语句、过程、变量,…};
模板
类同义词{…}
void evaluate(同义词s,同义词v){do something}
^所以我可以这样做。。。而不是检查输入函数,如:
void求值(同义词s,同义词v){
断言(s.type==语句);
断言(v.type==变量);
//还希望消除以下情况:(如果可能)
开关(s型){
案例XXX:doSomething。。。
案例YYY:不做任何事情。。。
}
}
您可以创建一个函数模板,然后专门处理该模板
template<typename Type>
void evaluate (Type t) {}
template<>
void evaluate<Statement>( Statement s)
{}
模板
void求值(类型t){}
模板
无效评估(报表s)
{}
这样,当您传递一个语句时,它将选择该重载,您可以根据类型执行不同的行为。我认为使用变体和访问者模式是合适的。看看Boost.Variant:,最后一个示例(也在下面,但已扩展)显示了一个访问者实现。还有其他变体和访问者实现。std::any和loki也是选项。我个人喜欢洛基,但这可能只是因为我是亚历山德雷斯库的超级粉丝
#include "boost/variant.hpp"
#include <iostream>
class ToLengthVisitor : public boost::static_visitor<int>
{
public:
int operator()(int i) const
{
return i;
}
int operator()(const std::string & str) const
{
return str.length();
}
int operator()(const char * str) const
{
const char * temp = str;
while(*temp != '\0') temp++;
return temp-str;
}
};
int main()
{
typedef boost::variant< int, std::string, const char * > MyVariant;
MyVariant u(std::string("hello world"));
std::cout << u; // output: hello world
MyVariant cu(boost::get<std::string>(u).c_str());
int result = boost::apply_visitor( ToLengthVisitor(), u );
std::cout << result; // output: 11 (i.e., length of "hello world")
result = boost::apply_visitor( ToLengthVisitor(), cu );
std::cout << result; // output: 11 (i.e., length of "hello world")
}
#包括“boost/variant.hpp”
#包括
类ToLengthVisitor:public boost::static\u visitor
{
公众:
int运算符()(int i)常量
{
返回i;
}
int运算符()(常量std::string&str)常量
{
返回str.length();
}
int运算符()(常量字符*str)常量
{
常量字符*temp=str;
而(*temp!='\0')temp++;
返回温度str;
}
};
int main()
{
typedef boost::variantMyVariant;
myvariantu(std::string(“helloworld”);
std::难道我不明白,你到底想实现什么?你总是可以重载函数参数,所以第一次求值应该可以。