小编Dav*_*veM的帖子

C++ Factory使用可变参数模板问题

我只想尝试一下 - 我想创建一个返回shared_ptr类型的通用工厂.

我有一个派生类,它使用静态方法将a返回shared_ptr给基类.我的想法是,我希望能够使用通用工厂注册这些方法,但它无法确定在编译时注册哪个方法.也许有一种方法可以使用SFINAE实现这一目标,但我刚刚开始了解它的复杂性.

对于相当长的代码示例表示歉意,也可以在http://coliru.stacked-crooked.com/a/331e08de86004592上找到

在'DerivedA'中启用多个工厂方法将导致编译错误.

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <memory>

// Factory which returns a shared_ptr of type T.
template<class T, class Tag, class... Args>
class NameFactory
{
public:
    typedef std::function<std::shared_ptr<T>(Args...)> Function;

    static NameFactory& instance();

    void registerType(const std::string& type, const Function& createFunction);
    std::shared_ptr<T> createObject(const std::string& type, Args&&... arguments);
private:
    NameFactory() {}

    std::unordered_map<std::string, Function> m_functionMap;
};

template<class T, class Tag, class... Args>
NameFactory<T, Tag, Args...>& NameFactory<T, Tag, Args...>::instance()
{
    static …
Run Code Online (Sandbox Code Playgroud)

c++ templates sfinae variadic-templates

7
推荐指数
1
解决办法
656
查看次数

在类中调用的重写的[]运算符的错误版本

我有一个简单的二维线类,它包含两个双精度矢量.我添加了getValue和setValue函数,但是更喜欢公共接口在这些函数旁边使用方括号运算符.以下代码显示了实现和使用:

#include <vector>
#include <algorithm>
#include <cassert>

class Simple2DLine
{
public:
    Simple2DLine();
    // Simple read method with linear interpolation
    double getValue(double x) const;
    // Simple write method, adds a curve point, keeping the arrays sorted
    void setValue(double x, double y);

    double& operator [](double x);
    const double operator [](double x) const;
private:
    std::vector<double> m_X;
    std::vector<double> m_Y;
    int getNearestIndex(double x) const;
};

Simple2DLine::Simple2DLine()
{

}

void Simple2DLine::setValue(double x, double y)
{
    // Get the index of the point at or just before …
Run Code Online (Sandbox Code Playgroud)

c++ const vector operators

1
推荐指数
1
解决办法
125
查看次数

标签 统计

c++ ×2

const ×1

operators ×1

sfinae ×1

templates ×1

variadic-templates ×1

vector ×1