I have classes Base, Derived1, Derived2, etc.
It is compilable (below).
class Base{ };
class Derived1 : public Base{
public: Derived1* operator->() { return this; }
public: void f1(){}
};
class Derived2 : public Base{
public: Derived2* operator->() { return this; }
};
class Derived3 : public Derived2{
public: Derived3* operator->() { return this; }
};
int main(){//test case (my objective is to make all these work)
Derived1 d1; d1->f1();
Base b=d1; //non harmful object slicing
Derived3 d3;
Derived2 d2=d3;
}
Edit: I believe it is a non-harmful object slicing, and I think it is unrelated to the question.
Then, I want the operator->() to be inside Base, so I don't have to implement in all DerivedX class.
This is my attempt so far, using CRTP. It is uncompilable at # :-
class Base{ };
template<class T1,class T2>class Helper{
public: T2* operator->() { return static_cast<T2*>(this); }
};
class Derived1 : public Helper<Base,Derived1>{
public: void f1(){}
};
class Derived2 : public Helper<Base,Derived2>{ };
class Derived3 : public Helper<Derived2,Derived3>{ };
int main(){
Derived1 d1; d1->f1();
Base b=d1; //#
Derived3 d3;
Derived2 d2=d3;
}
I have read these two promising links (below), and do little progress (above) :-
operator= and functions that are not inherited in C++?
Inheritance in curiously recurring template pattern polymorphic copy (C++)
Wiki states that casting Derive to Base is quite impossible for CRTP, so I feel that there might be no solution using CRTP.
Question:
How to move the operator-> to some kind of a base class to avoid code duplication?
(with or without CRTP are both OK)
Is there any solution using CRTP? In other words, is CRTP not suitable for this job?
I am new to CRTP (just play with it today). Sorry if it is duplicated.
Put aside the slicing of your objects, your example works just fine if you define your helper as:
template<class T1, class T2>
class Helper: public T1 {
public:
T2* operator->() {
return static_cast<T2*>(this);
}
};
That is:
Derive from T1 as if in a pure mixin based approach
Use T2 as if in a pure CRTP approach
If you consider the declaration of Derived1:
class Derived1: public Helper<Base, Derived1>;
It goes without saying that now Base b = d1; works, for Derived1 inherits directly from Base.
Related
In summary, I have a class inherited from std::enabled_shared_from_this, and there is a factory method return an std::unique_ptr of it. In another class, I convert the std::unique_ptr of the previous class object to std::shared_ptr, and then I call shared_from_this(), which then throws std::bad_weak_ptr. The code is shown below:
#include <memory>
#include <iostream>
struct Executor;
struct Executor1 {
Executor1(const std::shared_ptr<Executor>& executor,
int x): parent(executor) {
std::cout << x << std::endl;
}
std::shared_ptr<Executor> parent;
};
struct Backend {
virtual ~Backend() {}
virtual void run() = 0;
};
struct Executor: public Backend, public std::enable_shared_from_this<Executor> {
const int data = 10;
virtual void run() override {
Executor1 x(shared_from_this(), data);
}
};
// std::shared_ptr<Backend> createBackend() {
std::unique_ptr<Backend> createBackend() {
return std::make_unique<Executor>();
}
class MainInstance {
private:
std::shared_ptr<Backend> backend;
public:
MainInstance(): backend(createBackend()) {
backend->run();
}
};
int main() {
MainInstance m;
return 0;
}
Indeed changing std::unique_ptr<Backend> createBackend() to std::shared_ptr<Backend> createBackend() can solve the problem, but as I understand, in general, the factory pattern should prefer return a unique_ptr. Considering a good pratice of software engineering, is there a better solution?
[util.smartptr.shared.const]/1 In the constructor definitions below, enables shared_from_this with p, for a pointer p of type Y*, means that if Y has an unambiguous and accessible base class that is a specialization of enable_shared_from_this (23.11.2.5), then [magic happens that makes shared_from_this() work for *p - IT]
template <class Y, class D> shared_ptr(unique_ptr<Y, D>&& r);
[util.smartptr.shared.const]/29 Effects: ... equivalent to shared_ptr(r.release(), r.get_deleter())...
template<class Y, class D> shared_ptr(Y* p, D d);
[util.smartptr.shared.const]/10 Effects: ... enable shared_from_this with p
Your example executes std::shared_ptr<Backend>(uptr) where uptr is std::unique_ptr<Backend>, which is equivalent to std::shared_ptr<Backend>(p, d) where p is of type Backend*. This constructor enables shared_from_this with p - but that's a no-op, as Backend doesn't have an unambiguous and accessible base class that is a specialization of enable_shared_from_this
In order for Executor::enable_from_this to work, you need to pass to a shared_ptr constructor a pointer whose static type is Executor* (or some type derived therefrom).
Ok, I find a simple solution, that is, using auto as the return type of the factory function, instead of std::unique_ptr or std::shared_ptr, and keeping std::make_unique inside the factory function. The factory function createBackend should be:
auto createBackend() {
return std::make_unique<Executor>();
}
In this case, the return type can be automatically determined, although I don't know how it works exactly. This code can return either unique_ptr or shared_ptr, which should be better than just using shared_ptr. I tested clang and gcc, and both of them worked, but I am still not sure if this is gauranteed by the type deduction and the implicit conversion.
Update:
Actually, I have found that auto deduces the return type above as std::unique_ptr<Executor> instead of std::unique_ptr<Backend>, which might be the reason why the code works. But using auto has an issue: if you return the smart pointer in an if-else block, where the return type varies depending on some parameters, then auto cannot determine the type. For example:
std::unique_ptr<Backend> createBackend(int k = 0) {
if (k == 0) {
return std::make_unique<Executor>();
}
else {
return std::make_unique<Intepreter>();
}
}
Here, both Executor and Intepreter derive from Backend. I think a correct solution includes:
Inherit Backend instead of its derived classes from std::enable_shared_from_this;
Use dynamic_pointer_cast<Derived class> to cast the shared_ptr to derived class after shared_from_this.
The full code is listed in:
https://gist.github.com/HanatoK/8d91a8ed71271e526d9becac0b20f758
I am trying to templatize some of my code and am not sure if i am doing it correct way ?
template <typename T>
class User
{
public:
template <typename T>
void foo() {
A* pa = funcA();
OR
B* pb = funcB();
//common code follows
....
....
....
};
User<Atype> C1;
User<Btype> C2;
In the above code I am looking as to how to define foo() as to be able to use
either of A* pa = funcA() or B* pb = funcB() based on how the class is instantiated. C1 should be able to use A* pa = funcA() and C2 should be able to use B* pb = funcB().
Not directly, but there is various options. Normally it is best to avoid designs that result in needing different named functions, or conceptually different operations.
For example if both A and B had a member or static function foo, then you could call that (x.foo(), T::foo(), etc.) instead of having the separately named funcA and funcB. Or similarly, in the case of parameters you can use function overloading (as you can't overload on the return type), such as std::to_string, and sometimes using templates as well such as std::swap.
Otherwise, if you need to support completely different things, then there are many options.
You can specialise foo to have different implementations for different types. This is often not particularly ideal if you are planning to use many different types with a template function or class. In some cases you might specialise the entire class, and there is also partial specialisation.
class A {};
class B {};
A *funcA();
B *funcB();
template <typename T>
class User
{
public:
void foo();
};
template<> void User<A>::foo()
{
auto a = funcA();
// ...
}
template<> void User<B>::foo()
{
auto ab = funcB();
// ...
}
Similar to 1, you can have a separate template function or class that is specialised.
class A {};
class B {};
A *funcA();
B *funcB();
template<class T> T *funcGeneric();
template<> A *funcGeneric<A>() { return funcA(); }
template<> B *funcGeneric<B>() { return funcB(); }
template <typename T>
class User
{
public:
void foo()
{
auto p = funcGeneric<T>();
}
};
Or with a class, which can be useful if you have multiple methods or pieces of information. For a single method, the call operator is often overloaded.
template<class T> class FuncGeneric;
template<> class FuncGeneric<A>
{
public:
A *operator()()const { return funcA(); }
};
template<> class FuncGeneric<B>
{
public:
B *operator()()const { return funcB(); }
};
template <typename T>
class User
{
public:
void foo()
{
auto p = FuncGeneric<T>()();
}
};
Extending on 2, but you pass the "adapter" as a template parameter itself. This is one you see in the STL a fair bit, with things like std::map taking the Compare parameter (default std::less), unique_ptr taking a deleter (with std::default_delete calling delete), hash functions, etc.
template<class T> class FuncGeneric;
template<> class FuncGeneric<A>
{
public:
A *operator()()const { return funcA(); }
};
template<> class FuncGeneric<B>
{
public:
B *operator()()const { return funcB(); }
};
template <class T, class Func = FuncGeneric<T>>
class User
{
public:
void foo()
{
auto p = Func()();
}
};
In some cases you might pass the function itself. More common for functions rather than classes, for example many of the algorithms (e.g. find_if) do this.
template <class T, class Func>
class User
{
public:
User(Func func) : func(func) {}
void foo()
{
auto p = func();
}
private:
Func func;
};
int main()
{
User<A, A*(*)()> user(&funcA);
}
Functions can also be a template parameter themselves, although this is fairly uncommon.
template <class T, T*(*Func)()>
class User
{
public:
void foo()
{
auto p = Func();
}
};
int main()
{
User<A, &funcA> user;
}
Given the following code:
template< class T , class SIZE >
class Set {
T* a;
public:
...
...
class iterator {
..
..
};
class const_iterator {
..
..
};
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
};
How can I implement the iterator classes so that the following code will be valid?
Set<std::string, 5> set;
Set<std::string, 5>::const_iterator it=set.begin();
Namely, how can I implement the classes of the iterators so that I will be able to convert const_iterator to iterator?
You could use a converting constructor defined as such:
class const_iterator {
public:
const_iterator(iterator it) { /*...*/ }
};
or use a conversion operator as such:
class iterator {
public:
operator const_iterator() { return const_iterator(/*...*/); }
};
The most common way to implement the iterator/const_iterator pair though is by using a template like this:
template<typename T2>
class iterator_impl {
private:
// iterator info
public:
// conversion for const to non-const
operator iterator_impl<const T2>() { return iterator_impl<const T2>(/*...*/); }
};
// define the typedefs for const and non-const cases
typedef iterator_impl<T> iterator;
typedef iterator_impl<const T> const_iterator;
Obviously the last approach is the best, because you only have to implement the iterator functions one and since they only differ in the fact that one is const and the other isn't, then the argument T2 will take care of that.
Note. I haven't tested the above code, it's for viewing purposes only, but I believe it conveys the idea.
Update: I'm looking to see if there's a way to zero-initialize the entire class at once, because technically, one can forget adding a '= 0' or '{}' after each member. One of the comments mentions that an explicitly defaulted no-arg c-tor will enable zero-initialization during value-initialization of the form MyClass c{};. Looking at http://en.cppreference.com/w/cpp/language/value_initialization I'm having trouble figuring out which of the statements specify this.
Initialization is a complex topic now since C++11 has changed meaning and syntax of various initialization constructs. I was unable to gather good enough info on it from other questions. But see, for example, Writing a Default Constructor Forces Zero-Initialization?.
The concrete problem I'm facing is: I want to make sure members of my classes are zeroed out both for (1) classes which declare a default c-tor, and for (2) those which don't.
For (2), initializing with {} does the job because it's the syntax for value-initialization, which translates to zero-initialization, or to aggregate initialization if your class is an aggregate - case in which members for which no initializer was provided (all!) are zero-initialized.
But for (1) I'm still not sure what would be the best approach. From all info I gather I learned that if you provide a default c-tor (e.g. for setting some of the members to some values), you must explicitly zero remaining members, otherwise the syntax MyClass c = MyClass(); or the C++11 MyClass c{}; will not do the job. In other words, value-initialization in this case means just calling your c-tor, and that's it (no zero-ing).
You run into the same situation if you declare a c-tor that takes values, and sets those values to a subset of the members, but you'd like other members to be zero-ed: there is no shorthand for doing it - I'm thinking about 3 options:
class MyClass
{
int a;
int b;
int c;
MyClass(int a)
{
this->a = a;
// now b and c have indeterminate values, what to do? (before setting 'a')
// option #1
*this = MyClass{}; // we lost the ability to do this since it requires default c-tor which is inhibited by declaring this c-tor; even if we declare one (private), it needs to explicitly zero members one-by-one
// option #2
std::memset(this, 0, sizeof(*this)); // ugly C call, only works for PODs (which require, among other things, a default c-tor defaulted on first declaration)
// option #3
// don't declare this c-tor, but instead use the "named constructor idiom"/factory below
}
static MyClass create(int a)
{
MyClass obj{}; // will zero-initialize since there are no c-tors
obj.a = a;
return obj;
}
};
Is my reasoning correct?
Which of the 3 options would you choose?
What about using in-class initialization?
class Foo
{
int _a{}; // zero-it
int _b{}; // zero-it
public:
Foo(int a): _a(a){} // over-rules the default in-class initialization
};
Option 4 and 5:
option 4:
MyClass(int a) :a(a), b(0), c(0)
{
}
option 5:
class MyClass
{
int a = 0;
int b = 0;
int c = 0;
MyClass(int a) : a(a) {
}
}
In my humble opinion, the simplest way to ensure zero-initialization is to add a layer of abstraction:
class MyClass
{
struct
{
int a;
int b;
int c;
} data{};
public:
MyClass(int a) : data{a} {}
};
Moving the data members into a struct lets us use value-initialization to perform zero-initialization. Of course, it is now a bit more cumbersome to access those data members: data.a instead of just a within MyClass.
A default constructor for MyClass will perform zero-initialization of data and all its members because of the braced-initializer for data. Additionally, we can use aggregate-initialization in the constructors of MyClass, which also value-initializes those data members which are not explicitly initialized.
The downside of the indirect access of the data members can be overcome by using inheritance instead of aggregation:
struct my_data
{
int a;
int b;
int c;
};
class MyClass : private my_data
{
MyClass() : my_data() {}
public:
MyClass(int a) : MyClass() { this->a = a; }
};
By explicitly specifying the base-initializer my_data(), value-initialization is invoked as well, leading to zero-initialization. This default constructor should probably be marked as constexpr and noexcept. Note that it is no longer trivial. We can use initialization instead of assignment by using aggregate-initialization or forwarding constructors:
class MyClass : private my_data
{
public:
MyClass(int a) : my_data{a} {}
};
You can also write a wrapper template that ensures zero-initialization, thought the benefit is disputable in this case:
template<typename T>
struct zero_init_helper : public T
{
zero_init_helper() : T() {}
};
struct my_data
{
int a;
int b;
int c;
};
class MyClass : private zero_init_helper<my_data>
{
public:
MyClass(int a) { this->a = a; }
};
Having a user-provided constructor, zero_init_helper no longer is an aggregate, hence we cannot use aggregate-initialization any more. To use initialization instead of assignment in the ctor of MyClass, we have to add a forwarding constructor:
template<typename T>
struct zero_init_helper : public T
{
zero_init_helper() : T() {}
template<typename... Args>
zero_init_helper(Args&&... args) : T{std::forward<Args>(args)...} {}
};
class MyClass : private zero_init_helper<my_data>
{
public:
MyClass(int a) : zero_init_helper(a) {}
};
Constraining the constructor template requires some is_brace_constructible trait, which is not part of the current C++ Standard. But this already is a ridiculously complicated solution to the problem.
It is also possible to implement your option #1 as follows:
class MyClass
{
int a;
int b;
int c;
MyClass() = default; // or public, if you like
public:
MyClass(int a)
{
*this = MyClass{}; // the explicitly defaulted default ctor
// makes value-init use zero-init
this->a = a;
}
};
What about constructor delegation?
class MyClass
{
int a;
int b;
int c;
MyClass() = default; // or public, if you like
public:
MyClass(int a) : MyClass() // ctor delegation
{
this->a = a;
}
};
[class.base.init]/7 suggests that the above example shall invoke value-initialization, which leads to zero-initialization since the class does not have any user-provided default constructors [dcl.init]/8.2. Recent versions of clang++ seem to zero-initialize the object, recent versions of g++ do not. I've reported this as g++ bug #65816.
I would like to solve this issue about class member function callback.
Imagine you have a function from an external library (which cannot be modified!) like this:
void fortranFunction(int n, void udf(double*) );
I would like to pass as the udf function above a function member of an existing class. Please look at the following code:
// External function (tipically from a fortran library)
void fortranFunction(int n, void udf(double*) )
{
// do something
}
// User Defined Function (UDF)
void myUDF(double* a)
{
// do something
}
// Class containing the User Defined Function (UDF)
class myClass
{
public:
void classUDF(double* a)
{
// do something...
};
};
int main()
{
int n=1;
// The UDF to be supplied is myUDF
fortranFunction(n, myUDF);
// The UDF is the classUDF member function of a myClass object
myClass myClassObj;
fortranFunction(n, myClassObj.classUDF); // ERROR!!
}
The last line of the code above results in a compilation error, because you cannot declare the classUDF member function as a static function.
Do you know if it is possible to solve this issue?
Probably Boost libraries could help me, but I do not know how (please consider that fortranFunction cannot be modified because is from an external library).
Thanks a lot!
Alberto
I don't understand, why can't you declare classUDF as static like this
class myClass {
public:
static void classUDF(double *a) {
...
}
};
and then pass it like
fortranFunction(n, myClass::classUDF);
You might try that solution (a little bit hacky, but I think, it should work for you):
void fortranFunction(int n, void udf(double*))
{
double d = static_cast<double>(n);
udf(&d);
}
class myClass {
public:
void classUDF(double* a) {
}
};
#ifdef _MSC_VER
#define THREADLOCALSTATIC __declspec(thread) static
#define THREADLOCAL
#else
#define THREADLOCALSTATIC static ___thread
#define THREADLOCAL ___thread
#endif
struct _trampolinebase {
THREADLOCALSTATIC _trampolinebase* current_trampoline;
};
THREADLOCAL _trampolinebase* _trampolinebase::current_trampoline = 0;
#undef THREADLOCAL
#undef THREADLOCALSTATIC
template<class CBRET, class CBARG1, class T>
struct _trampoline1 : _trampolinebase
{
typedef CBRET (T::*CALLBACKFN)(CBARG1);
_trampoline1(T& target, CALLBACKFN& callback)
: callback_(callback)
, target_(target)
{
assert(current_trampoline == 0);
current_trampoline = this;
}
static CBRET callback(CBARG1 a1) {
_trampoline1* this_ = static_cast<_trampoline1*>(current_trampoline);
current_trampoline = 0;
return this_->trampoline(a1);
}
private:
CBRET trampoline(CBARG1 a1) {
return (target_.*callback_)(a1);
}
CALLBACKFN& callback_;
T& target_;
};
template<class FRET, class FARG1, class CBRET, class CBARG1, class T, class F>
FRET call1_1(T& target, CBRET (T::*callback)(CBARG1), F& fortranfunction, FARG1 a)
{
typedef typename _trampoline1<CBRET, CBARG1, T> trampoline;
trampoline t(target, callback);
return fortranFunction(a, trampoline::callback);
}
int main()
{
int n=1;
myClass myClassObj;
call1_1<void,int,void,double*>(myClassObj, &myClass::classUDF, fortranFunction, 1);
}
With the 'threadlocal' stuff, this will work in multithreaded calls, too. You may omit that, if you don't use a multithreaded environment. It also works with recursive calls (e.g. if the callback calls another fortran function).
This solution works only for one single argument plus callback for the fortran function and one single argument in the callback function itself, but you should be able to extend it easily. This is also, why I called it 'call1_1' (fortran function with 1 argument, callbackfunction with 1 argument). FRET is the return type of the fortran function, FARG1 the type of the first argument (int in this case). CBRET and CBARG are the same for the callback function.
Before the fortran function is actually called, the target object is stored within a global (thread-local) variable. The fortran function calls a static callback function, which finally calls your member function.
I invented the trampolinebase to instantiate the static member, I could also have used a global variable for that (but for some reason, I don't like global variables too much) ;-)