C ++:模板模板需要手动指定模板类型

时间:2014-02-14 00:49:47

标签: c++ templates

所以我编写了一个模板,该模板取决于另一个模板的类型(参见下面的print_visit)。这显然是代码的一个片段;我只包含了足够的内容来理解上下文。我的问题是:有没有办法让我编写print_visit,以便我的绑定调用看起来像std::bind(print_visit,"BFS",_1)而不是下面代码中看到的详细调用?

class digraph {
public:
    typedef char nodename;
    struct edge {
        nodename from;
        nodename to;
        int weight;
    };
    digraph( const set<nodename> &vertices, const vector<edge> & edges );
    vector<nodename> dfs( const nodename vertex );
    vector<nodename> bfs( const nodename vertex );
    deque<nodename> dijkstra( const nodename origin, const nodename destination);
private:
};

template< typename T,
          template<typename El, typename Alloc=std::allocator<El> > class Container >
ostream &operator<< (ostream &ostr, const Container<T> &xs)
{
    ostr << "{ ";
    for ( auto &x : xs )
        ostr << x << ",";
    ostr << " }";
    return ostr;
}

template< typename T,
          template<typename El, typename Alloc=std::allocator<El> > class Container >
void print_visit( const char* title, const Container<T> &xs)
{
    cout << title << " visiting ";
    cout << xs;
    cout << endl;
};


int main( int argc, char *argv[] )
{
    // would like to do:
    // auto bfs_visit = std::bind( print_visit, "BFS", _1 );
    auto bfs_visit = std::bind( print_visit<digraph::nodename,vector>,
                                "BFS", _1);
    auto dfs_visit = std::bind( print_visit<digraph::nodename,vector>,
                                "DFS", _1);
    auto topsort_visit = std::bind( print_visit<digraph::nodename,vector>,
                                    "Topsort", _1);
    auto dijkstra_visit = std::bind( print_visit<digraph::nodename,deque>,
                                    "Dijkstra", _1);

    auto some_tests = [&] (digraph &g, digraph::nodename source,
                           digraph::nodename destination)
        { bfs_visit(g.bfs(source));
          dfs_visit(g.dfs(source));
          dijkstra_visit(g.dijkstra(source,destination)); };
}

0 个答案:

没有答案