我有以下代码。我必须为 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”语句吗?
最佳答案
bool operator()(std::string const& other ) const {...}
template< class T >
typename boost::disable_if<boost::is_same<T, std::string>, bool >::type
operator()( T const& ) const {return false;}
关于c++ - 是否可以使用模板来识别两种不同的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13266302/