c++ - 如何为子函数指定模板参数?

标签 c++ templates inheritance virtual-functions function-templates

所以我尝试:

class data_ppp {
public:
    template <class T>
    virtual boost::shared_ptr<T> getData()
    {
        return boost::shared_ptr<T>(new T());
    }
};

class data_child : public data_ppp {
public:
    template<>
    getData<std::vector<int>>();
};

但无法获得预期的效果 - 我想在类 data_child getData 函数中只返回 boost::shared_ptr<std::vector<int>> .怎么办?

最佳答案

我现在看到的解决您问题的唯一方法是:

class data_ppp
{
public:
    template<class T>
    std::shared_ptr<T> getData()
    { return std::shared_ptr<T>(new T()); }
};

class data_child : public data_ppp
{
public:
    std::shared_ptr<int> getData() 
    { return data_ppp::getData<int>(); }
};

用法:

data_child dc;
dc.getData();
//dc.getData<float>(); // compilation error

关于c++ - 如何为子函数指定模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14443092/

相关文章:

c++ - 反序列化时出现微小的 xml 空点引用错误?

c++ - 什么时候使用重载赋值运算符?

c++ - 将没有定义的 static const int 的地址传递给模板是否合法?

c++ - 初学者 C++ 继承

java - 是否有一种设计模式可以创建只有一些值不同的原型(prototype)?

c++ - Makefile:根据 CC/CXX/FC 值更改编译器标志

c++ - 单一模板参数的特化

templates - 如何将新模板添加到 Typo3 "Layouts"下拉列表

c++ - 如何构建遗传算法类层次结构?

C++ function_pointer 和 &function_pointer 有什么区别?