How to add a method to 2 classes by using templates?

I have 2 very simple classes and both need to perform a canDelete() method. How can I "insert" such method so I only define it once and also without the overhead of runtime polymorphism?

The classes are:
1
2
3
4
5
6
7
8
9
10
11
12
13
struct Statement
{
	int id_statement;
	date::sys_days date;
        bool canDelete();
};
struct Concepto
{
	int id_concepto;
	std::string name;
	int fkey_account;
        bool canDelete();
};


bool canDelete() is implemented exactly the same so I don't want to duplicate its code and I want to use templates to achieve this (i do not want runtime polymorphism).

Something like this code would apparently work but it does not compile (you can get the gist by looking at this):

1
2
3
4
5
6
7
8
9
10
11
12
template<typename Table>
struct RefIntegrity : Table
{
	bool canDelete()
	{
		return ! RecordLinks::has_links(*this);
	}
};

 /// and then
struct Statement : RefIntegrity<Statement>
{...}



What am I missing?

Thanks
Juan
I found one possible solution and would like to share it with you guys:

Define RefIntegrity like so:

1
2
3
4
5
6
7
8
template<typename Table>
struct RefIntegrity 
{
	bool canDelete()
	{
		return ! RecordLinks::has_links( static_cast<Table&>(*this));
	}
};


and inherit into the structs like so:

1
2
3
4
5
6
7
8
9
10
11
struct Statement : RefIntegrity<Statement>
{
	int id_statement;
	date::sys_days date;
};
struct Concepto : RefIntegrity<Concepto>
{
	int id_concepto;
	std::string name;
	int fkey_account;
};



Now both Statement and Concepto share the one definition of canDelete provided by RefIntegrity...

Only one sad issue, aggregate initialization must now include empty braces for the superclass Refintegrity like so:

 
Statement statement{ {}, - 1, ttod };


Any other solutions to this puzzle?

Regards,
Juan
Function overloading?
1
2
3
4
template <typename T> bool canDelete(T const& x)
{
  return !RecordLinks::has_links(std::addressof(x));
}
and both need to perform a canDelete() method


Why a method? What about just a stand-alone function taking a class as a templated parameter? Not everything needs to be a class member.
I created a RefIntegrityManager class with a canDelete template method and others. It is better to put the responsability in a class apart.

Thanks for the input!

Juan


Topic archived. No new replies allowed.