Jasmine
Jasmine

Reputation: 16185

Would C++ templates help reuse very similar code?

I have to admit that I steer clear of templates as much as possible. I want to change that. They shouldn't be so scary.

If I have functions declared like:

std::vector<SQLFieldObject> executeSelectQueryReturnSingleInt(std::string _sql);
std::vector<SQLPlantObject> executeSelectQueryReturnSingleInt(std::string _sql);
std::vector<SQLOrderObject> executeSelectQueryReturnSingleInt(std::string _sql);   

Where in executeSelectQueryReturnSingleInt(std::string _sql) The code is exactly the same for each function. I create a local version of the std::vector and return it.

I'd like to just have one generic executeSelectQueryReturnSingleInt(std::string _sql) function.

Templates might solve this, correct? Looking at example templates

template <class SomeType>
SomeType sum (SomeType a, SomeType b)
{
     return a+b;
}

What is confusing is that the parameters going in are the same, except the return vector is different.

Can anyone help me understand how to start applying templates to code reuse?

Upvotes: 2

Views: 256

Answers (2)

nneonneo
nneonneo

Reputation: 179452

You can do that:

template<typename SQLObject>
std::vector<SQLObject> executeSelectQueryReturnSingleInt(std::string _sql) {
    ...
}

then you call it as, for example,

executeSelectQueryReturnSingleInt<SQLPlantObject>("rose");

Note that you have to explicitly specify the template arguments because they can't be deduced from the function arguments, but otherwise this works like you'd expect.

Upvotes: 4

juanchopanza
juanchopanza

Reputation: 227418

In this particular case, the template parameter would be the return type. You then have to use it explicitly when calling the function because it cannot be deduced from the function parameters:

template <typename ReturnType>
ReturnType executeSelectQueryReturnSingleInt(std::string sql)
{
     return ReturnType(args....);
}

Then

auto x = executeSelectQueryReturnSingleInt<std::vector<SQLFieldObject>>(sqlstr);

If you only want to return an std::vector of a particular type, then

template <typename SQLObjType>
std::vector<SQLObjType> executeSelectQueryReturnSingleInt(std::string sql)
{
     return std::vector<SQLObjType>(args....);
}

and

auto x = executeSelectQueryReturnSingleInt<SQLFieldObject>(sqlstr);

Upvotes: 2

Related Questions