c++ - 是否可以使用模板来识别两种不同的类型?

标签 c++ templates boost

我有以下代码。我必须为 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/

相关文章:

c++ - boost::split 与 boost::iter_split 之间的区别

c++ - 多个 OpenGL 纹理在某些情况下不起作用?

c++ - 如何读取 gmon.out?

c++ - 函数模板的实例化

c++ - G++ 模板实例化导致 "Undefined reference to"错误

c++ - 如何将 boost 与 xeus-cling jupyter 内核结合使用?

c++ - 从数组中向量化提取特定模式的短裤,并插入到新数组中

c++ - std::shared_ptr 迭代器

c++ - 模板赋值运算符不会替换默认的赋值运算符

python - SWIG 和 Boost::变体