Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a function instead of copy-and-paste programming

Tags:

c++

I have an object, every member variable in this object has a name which I can acquire it by calling get_name() ,what I want to do is concatenate all the names of the member variables in alphabetical order, then do something. for example:

class CXMLWrapper<class T>
{
public:
    CXMLWrapper(const char* p_name) : m_local_name(p_name)
    {
    }
    //skip the get_name(), set_name() and others    
private:
    string m_local_name;
    T m_type_var;
}
class object
{
public:
    object() : m_team("team"), m_base("base")
    {
    }
public:
    CXMLWrapper<string> m_team;
    CXMLWrapper<string> m_base;
...
}

I have to hard-code like this:

object o;
string sign = o.m_base.get_name();
sign += o.m_team.get_name();

I need a function to do this instead of copying and pasting when the object varies. Anyone has an idea?

like image 830
jfly Avatar asked Aug 06 '13 08:08

jfly


People also ask

What are the functions to copy and paste?

Select the text you want to copy and press Ctrl+C. Place your cursor where you want to paste the copied text and press Ctrl+V.

Why is a function better than copy/pasting code in Python?

With copy and paste, YOU are reusing code. With a function, the computer is reusing the logic. Of course, you can write code that calls a function, or you can write a function, but copy and paste is a programming practice while functions are part of the code.

Is copy and paste programming really a problem?

Being a form of code duplication, copy-and-paste programming has some intrinsic problems; such problems are exacerbated if the code doesn't preserve any semantic link between the source text and the copies. In this case, if changes are needed, time is wasted hunting for all the duplicate locations.


1 Answers

One way to do this in normal C++, provided all of the members belong to the same class or are derived from some base class will be to use variable number of arguments to a function. An example follows.

#include <stdarg.h>
string concatenateNames(int numMembers, ...)
{
    string output;
    va_list args;
    va_start(args, numMembers);
    for(int i = 0; i < numMembers; i++)
    {
        MemberClass *pMember = va_arg(args, MemberClass*);
        output += pMember->get_name();
    }
    va_end(args);
    return output;
}

class Object
{
    public:
        MemberClass x;
        MemberClass y;
        MemberClass z;
};

int main()
{
    Object o;
    string sign = concatenateNames(3, &o.x, &o.y, &o.z);
}

If the types of all the members are different, you can look into variadic templates of C++11x: http://en.wikipedia.org/wiki/Variadic_Templates, but I can't seem to find a way to do otherwise.

like image 68
Subhasis Das Avatar answered Sep 23 '22 03:09

Subhasis Das