【发布时间】:2012-11-07 09:02:05
【问题描述】:
我有以下代码。我必须为MyVariant 中可用的所有类型(bool、int、string、const char*)定义operator()。但是,由于StartsWith 仅适用于字符串类型,所有其他仿函数都应返回 false。
#include "boost/variant/variant.hpp"
#include "boost/variant/apply_visitor.hpp"
using namespace std;
using namespace boost;
typedef variant<bool, int, string, const char*> MyVariant;
class StartsWith
: public boost::static_visitor<bool>
{
public:
string mPrefix;
bool operator()(string &other) const
{
return other.compare(0, mPrefix.length(), mPrefix);
}
bool operator()(int &other) const
{
return false;
}
bool operator()(bool &other) const
{
return false;
}
bool operator()(const char* other) const
{
return false;
}
StartsWith(string const& prefix):mPrefix(prefix){}
};
int main(int argc, char **argv)
{
MyVariant s1 = "hello world!";
if(apply_visitor(StartsWith("hel"), s1))
{
cout << "starts with" << endl;
}
return 0;
}
上面的代码工作正常。但是为了使其更简洁,我认为可以使用模板来为字符串提供一个函子,而为其他类型提供一个函子。我尝试了以下方法,但结果是第二个仿函数总是被调用的。
template<typename T>
class StartsWith
: public boost::static_visitor<bool>
{
public:
T mPrefix;
bool operator()(T &other) const
{
return other.compare(0, mPrefix.length(), mPrefix);
}
template<typename U>
bool operator()(U &other)const
{
return false;
}
StartsWith(T const& prefix):mPrefix(prefix){}
};
以下代码也不起作用:
class StartsWith
: public boost::static_visitor<bool>
{
public:
string mPrefix;
bool operator()(string &other) const
{
return other.compare(0, mPrefix.length(), mPrefix);
}
template<typename U>
bool operator()(U &other)const
{
return false;
}
StartsWith(string const& prefix):mPrefix(prefix){}
};
我是否可以避免字符串以外的类型出现多个“return false”语句?
【问题讨论】:
-
“hel”类型是
const char*,而不是string。 -
template<typename U> bool operator()(U &other)const为我工作。这可能是因为您使用的是const char*。