成员函数重载/模板特化问题

Fer*_*cio 4 c++ templates overloading specialization

我一直试图调用重载的table::scan_index(std::string, ...)成员函数但没有成功.为了清楚起见,我删除了所有不相关的代码.

我有一个被调用的类table,它有一个重载/模板化的成员函数scan_index(),以便将字符串作为特例处理.

class table : boost::noncopyable
{
public:
    template <typename T>
    void scan_index(T val, std::function<bool (uint recno, T val)> callback) {
        // code
    }

    void scan_index(std::string val, std::function<bool (uint recno, std::string val)> callback) {
        // code
    }
};
Run Code Online (Sandbox Code Playgroud)

然后有一个hitlist类,它有许多调用的模板化成员函数table::scan_index(T, ...)

class hitlist {
public:
    template <typename T>
    void eq(uint fieldno, T value) {
        table* index_table = db.get_index_table(fieldno);
        // code
        index_table->scan_index<T>(value, [&](uint recno, T n)->bool {
            // code
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

最后,代码全部启动:

hitlist hl;
// code
hl.eq<std::string>(*fieldno, p1.to_string());
Run Code Online (Sandbox Code Playgroud)

问题是它不是调用table::scan_index(std::string, ...),而是调用模板化版本.我尝试过使用重载(如上所示)和专门的函数模板(如下所示),但似乎没有任何效果.在盯着这段代码几个小时之后,我觉得我错过了一些明显的东西.有任何想法吗?

    template <>
    void scan_index<std::string>(std::string val, std::function<bool (uint recno, std::string val)> callback) {
        // code
    }
Run Code Online (Sandbox Code Playgroud)

更新:<T>scan_index()通话中删除了装饰.结果是使用字符串参数的调用编译得很好,但是使用其他类型(例如double)调用会导致以下错误:

cannot convert parameter 1 from 'double' to 'std::string'
Run Code Online (Sandbox Code Playgroud)

所以我回到使用模板专业化.现在我收到这个错误:

error C2784: 'void table::scan_index(T,std::tr1::function<bool(uint,T)>)' :
  could not deduce template argument for 'std::tr1::function<bool(uint,T)>'
  from '`anonymous-namespace'::<lambda5>'
Run Code Online (Sandbox Code Playgroud)

仅供参考:我使用的是VC++ 10.0

解决方案: 我通过scan_index()table类中删除模板化函数并简单地编写四个重载函数来解决这个问题(其中三个函数除了签名之外是相同的).幸运的是,它们都很短(少于十行),所以它并不是那么糟糕.

Nik*_*sov 7

您在此明确调用模板化成员:

index_table->scan_index<T>(value, [&](uint recno, T n)...
Run Code Online (Sandbox Code Playgroud)

既然value是模板参数,你可以用以下方法替换它:

index_table->scan_index(value, [&](uint recno, T n)...
Run Code Online (Sandbox Code Playgroud)