Reputation: 1321
Is there a way to achieve anything similar to this in C++:
template<typename SomeClass>
auto SomeClass::someMemberFunction() { ... }
The idea being that if the given member function is declared in a class but not defined, it will get the default definition from this template.
Upvotes: 0
Views: 197
Reputation: 31
On my knowledge, the template type cannot work in this case. You wrote definition of template function, but you need the declaration. Declaration you can write as a one body-one part, NOT of some class members like:
class A {
//some members
};
class A { //redefinition, not possible "partial class" like in C#
//the other members
};
The solution would be inheritance, but here you don't need templates:
#include <iostream>
using namespace std;
class Base{
protected:
Base(){}
public:
int someMemberFunction() {
return 5;
}
};
class A: public Base{
public:
int X(){
return x;
}
void setX(int _x){
x=_x;
}
private:
int x;
};
int main(){
A a;
a.setX(3);
//Base b; Base() is protected
cout <<"a.x="<<a.X()<<endl;
cout <<"a.someMemberFunction(): "<<a.someMemberFunction()<<endl;
return 0;
}
Upvotes: 1
Reputation: 25623
You can simply add a general base class as this:
class DefaultsAsBase
{
public:
void Bla() { std::cout << "Bla" << std::endl; }
void Blub() { std::cout << "Blub" << std::endl; }
};
template < typename T>
class TemplatedOnes: public DefaultsAsBase
{
public:
void Bla() { std::cout << "templated Bla" << std::endl; }
};
// and the specialized if needed
template <>
class TemplatedOnes<int>: public DefaultsAsBase
{
public:
void Blub() { std::cout << "Specialized Blub" << std::endl; }
};
int main()
{
TemplatedOnes<float> tf;
TemplatedOnes<int> ti;
tf.Bla();
tf.Blub();
ti.Bla();
ti.Blub();
}
If you like, you can add the base class as a parameter to your template, which makes it partly CRTP. Real CRTP have also casts to the deriving class, which is not part of your question, but if you like, you can add it.
class DefaultsAsBase
{
public:
void Bla() { std::cout << "Bla" << std::endl; }
void Blub() { std::cout << "Blub" << std::endl; }
};
class OtherDefaultAsBase
{
void Bla() { std::cout << "Bla other" << std::endl; }
void Blub() { std::cout << "Blub other" << std::endl; }
};
template < typename T, class CRTP_BASE>
class TemplatedOnes: public CRTP_BASE
{
public:
void Bla() { std::cout << "templated Bla" << std::endl; }
};
// and the specialized if needed
template <typename CRTP_BASE>
class TemplatedOnes<int, CRTP_BASE>: public DefaultsAsBase
{
public:
void Blub() { std::cout << "Specialized Blub" << std::endl; }
};
int main()
{
TemplatedOnes<float, DefaultsAsBase> tf;
TemplatedOnes<int, DefaultsAsBase> ti;
TemplatedOnes<int, OtherDefaultAsBase> ti2;
tf.Bla();
tf.Blub();
ti.Bla();
ti.Blub();
ti2.Bla();
ti2.Blub();
}
Upvotes: 1