c++ - 将 set<template T> 作为参数传递时出错

标签 c++ templates stl

我正在尝试将“通用集”作为参数传递。

template<class T>
class Printer {
public:
    static doprint (std::set < T >& ms){

        for (std::set::const itr = ms.begin(); itr!= ms.end(); ++itr)
        {
            //do processing. e.g. printing
            cout<< ms.print(); 
        }
        ms.clear();
    }
};

我调用方法使用

std::set <classA> setA; //both class A and B have a .print() method
std::set <classB> setB;
    // populates A & B

Printer::doPrint(setA);
Printer::doPrint(setB);

但我收到以下错误

error: 'template <class T> class Printer' used without template parameters.

知道如何解决这个问题吗?

最佳答案

因为模板在类上,所以在调用doPrint的时候要显式的调用出来:

Printer<classA>::doPrint(setA) ;

通常为了解决这个问题,人们会制作可以自己找出模板参数的辅助函数:

template <class T>
  void call_doprint(std::set < T >& ms) { Printer<T>::doPrint( ms) ; } 

然后你可以调用:

call_doprint( setA) ;

这是人们喜欢 make_sharedptrmake_pair 比调用构造函数更好的原因之一。

关于c++ - 将 set<template T> 作为参数传递时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20260143/

相关文章:

c++ - 迭代 vector 的 vector

C++ Map 在尝试设置值时出现总线错误

c++ - Visual C++ 2015 中的 CSpice : Link errors

c++ - 如何在 XCode 中调试 DYLIB?

c++ - 如何解决 MSVC 2012 中的 `using K = ...`?

c++ - 使用 SFINAE 检测模板化成员函数的存在

c++ - std::map 是否自动平衡自身

c++ - 更改原始 vector 不会在集合中更改它

C++0x : how to get variadic template parameters without reference?

c++ - 在 C++ 中寻找 MemoryStream