Skip to content

Adding attributes to tags in svg backend #72

@fcooper8472

Description

@fcooper8472

I would like to implement some helper to make this kind of thing look less nasty (easier to read, reason about, and maintain):

m_out << "x=\"" << min[0] << "\" y=\"" << min[1] << "\" width=\"" << delta[0] << "\" height=\"" << delta[1] << "\" ";

There are several possible options.

1. Function template, something like:

template<typename T>
std::string att(const std::string& name, const T val)
{
  std::stringstream ss;
  ss << std::setprecision(5) << name << "=\"" << val << "\" ";
  return ss.str();
}

so that the above example becomes

m_out << att("x", min[0]) << att("y", min[1]) << att("width", delta[0]) << att("height", delta[1]); 

This looks quite nice, and is certainly much easier to read. But, the overhead of generating lots of stringstream objects and returning strings is high (~2x slower). Speed probably isn't a massive concern at this stage, but let's avoid massive slowdowns if there's a better option.

2. As above, but sending straight to m_out:

I don't like this option at all, because the example becomes:

att("x", min[0]); att("y", min[1]); att("width", delta[0]); att("height", delta[1]); 

It's super unclear at a glance what's happening and doesn't have any flexibility at all.

3. A small class for gathering attributes:

struct attribs {
  std::stringstream ss;
  attribs& add(const std::string& name, const float val) {
    ss << std::setprecision(5) << name << "=\"" << val << "\" ";
    return *this;
  }
  /* overload << */
};

The example becomes

attribs att;
att.add("x", min[0]).add("y", min[1]).add("width", delta[0]).add("height", delta[1]);
m_out << att;

This has a greatly reduced cost vs 1, is flexible, but perhaps not the most elegant.

@martinjrobins Any other ideas for how this might look?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions