How do I cast a vtkSmartPointer<T> to an inherited class while maintaining reference counting?
Minimal illustration:
#include <iostream>
#include <vtkSmartPointer.h>
class A: public vtkObjectBase {
public :
A(){}
static A * New(){return new A();}
int var1 = 8;
};
class B: public A {
public :
B(){}
static B * New() {return new B();}
int var2 = 12;
};
int main (int argc, char ** argv) {
vtkSmartPointer<B> b = vtkSmartPointer<B>::New();
vtkSmartPointer<A> a = b; // this is fine
std::cout << "var1 = " << a->var1 << std::endl;
// this is not fine and I cannot find a vtk equivalent
// to boost's dynamic_pointer_cast for similar functionality
// vtkSmartPointer<B> c = a; // how do I do this?
}
I'm assuming there must be a macro somewhere similar to boost's dynamic_pointer_cast<T> but I can't find it. If there isn't, and someone can suggest a method to accomplish this, I would be very grateful.
There are a couple of problems here.
In most cases you want to inherit from vtkObject, not vtkObjectBase.
You are missing vtkTypeMacro().
What you are looking for is T::SafeDownCast().
So your code would become:
#include <vtkSmartPointer.h>
class A : public vtkObject {
public :
vtkTypeMacro(A, vtkObject);
A() = default;
static A* New() { return new A(); }
int var1 = 8;
};
class B : public A {
public:
vtkTypeMacro(B, A);
B() = default;
static B* New() { return new B(); }
int var2 = 12;
};
int main (int argc, char ** argv) {
vtkSmartPointer<B> b = vtkSmartPointer<B>::New();
vtkSmartPointer<A> a = b;
vtkSmartPointer<B> c = B::SafeDownCast(a);
}
For more information, please, consult VTK User Guide, chapter "14.6 Writing A VTK Class".
Okay nevermind, I found an answer that appears to work. I'll post it in case someone stumbles across here and wants to avoid the frustration I had.
It turns out that reference counting happens in the vtkObjectBase. So as long as code inherits from that, vtk will keep an accurate count. Thankfully vtk won't let you use vtkSmartPointer unless it does.
So it would seem that to implement a boost style macro one could simply do the following:
template<typename T,typename V> vtkSmartPointer<T> vtkDynamicPointerCast(vtkSmartPointer<V> src) {
T* v = dynamic_cast<T*>(src.Get());
if (v) return vtkSmartPointer<T>(v);
else return vtkSmartPointer<T>();
}
Related
class Dummy
{
public:
int* A{};
int num{};
public:
Dummy(int num)
{
this->num = num;
A = new int[num];
}
~Dummy()
{
delete[] A;
}
};
Dummy* dummy()
{
Dummy* d = new Dummy{ 4 };
d->A[0] = 1;
d->A[1] = 2;
d->A[2] = 3;
d->A[3] = 4;
return d;
}
int main()
{
Dummy* ATT = dummy();
}
When I tired to run this program This is always showing Expection at destructor and program can't continue further. What's wrong in this Code...
Your code uses new() and delete() which nowadays in C++ should mostly never be used. Please make yourself comfortable with the appropriate pointer classes which handle memory management for you, like shared_ptr or unique_ptr.
I'm trying to declare a friend function of a class with static members. I compiled my program in Visual Studio 2017 and faced this compile-time error:
unresolved external symbol "private: static struct Number * user::Link" (?Link#user##0PAUNumber##A)
Here's my code:
#include<iostream>
using namespace std;
typedef struct Number
{
int number;
struct Number *Link;
}
num_t;
class user
{
private:
static num_t *Link;
static int Length;
public:
static void Create()
{
cout << "You called a function." << endl;
Link->number = 1;
}
friend void Show_menu();
};
void Show_menu()
{
user::Create();
}
int user::Length = 1;
num_t user::*Link = nullptr;
int main()
{
return 0;
}
Generally, Is it possible to define a friend function of a class with static members in C++? If so, how do I fix the problem above?
I think you wanted num_t* user::Link = nullptr;.
The error has nothing to do with the declared friend.
Historically, I've been using trait classes to hold information and apply that into a "generic" function that runs the same "algorithm." Only differed by the trait class. For example: https://onlinegdb.com/ryUo7WRmN
enum selector { SELECTOR1, SELECTOR2, SELECTOR3, };
// declaration
template < selector T> struct example_trait;
template<> struct example_trait<SELECTOR1> {
static constexpr size_t member_var = 3;
static size_t do_something() { return 0; }
};
template<> struct example_trait<SELECTOR2> {
static constexpr size_t member_var = 5;
static size_t do_something() { return 0; }
};
// pretend this is doing something useful but common
template < selector T, typename TT = example_trait<T> >
void function() {
std::cout << TT::member_var << std::endl;
std::cout << TT::do_something() << std::endl;
}
int main()
{
function<SELECTOR1>();
function<SELECTOR2>();
return 0;
}
I'm not sure how to create "generic" algorithms this when dealing with polymorphic classes.
For example: https://onlinegdb.com/S1hFLGC7V
Below I have created an inherited class hierarchy. In this example I have a base catch-all example that defaults all the parameters to something (0 in this case). And then each derived class sets overrides specific methods.
#include <iostream>
#include <memory>
#include <type_traits>
#include <assert.h>
using namespace std;
struct Base {
virtual int get_thing_one() {
return 0;
}
virtual int get_thing_two() {
return 0;
}
virtual int get_thing_three() {
return 0;
}
virtual int get_thing_four() {
return 0;
}
};
struct A : public Base {
virtual int get_thing_one() override {
return 1;
}
virtual int get_thing_three() override {
return 3;
}
};
struct B : public Base {
virtual int get_thing_one() override {
return 2;
}
virtual int get_thing_four() override{
return 4;
}
};
Here I created a simple factory, not elegant but for illustrative purposes
// example simple factory
std::shared_ptr<Base> get_class(const int input) {
switch(input)
{
case 0:
return std::shared_ptr<Base>(std::make_shared<A>());
break;
case 1:
return std::shared_ptr<Base>(std::make_shared<B>());
break;
default:
assert(false);
break;
}
}
So this is the class of interest. It is a class does "something" with the data from the classes above. The methods below are a simple addition example but imagine a more complicated algorithm that is very similar for every method.
// class that uses the shared_ptr
class setter {
private:
std::shared_ptr<Base> l_ptr;
public:
setter(const std::shared_ptr<Base>& input):l_ptr(input)
{}
int get_thing_a()
{
return l_ptr->get_thing_one() + l_ptr->get_thing_two();
}
int get_thing_b()
{
return l_ptr->get_thing_three() + l_ptr->get_thing_four();
}
};
int main()
{
constexpr int select = 0;
std::shared_ptr<Base> example = get_class(select);
setter l_setter(example);
std::cout << l_setter.get_thing_a() << std::endl;
std::cout << l_setter.get_thing_b() << std::endl;
return 0;
}
How can I make the "boilerplate" inside the setter class more generic? I can't use traits as I did in the example above because I can't tie static functions with an object. So is there a way to make the boilerplate example more common?
Somewhere along the lines of having a selector, say
enum thing_select { THINGA, THINGB, };
template < thing_select T >
struct thing_traits;
template <>
struct thing_traits<THINGA>
{
static int first_function() --> somehow tied to shared_ptr<Base> 'thing_one' method
static int second_function() --> somehow tied to shared_ptr<Base> 'thing_two' method
}
template <>
struct thing_traits<THINGB>
{
static int first_function() --> somehow tied to shared_ptr<Base> 'thing_three' method
static int second_function() --> somehow tied to shared_ptr<Base> 'thing_four' method
}
// generic function I'd like to create
template < thing_select T, typename TT = thing_traits<T> >
int perform_action(...)
{
return TT::first_function(..) + TT::second_function(..);
}
I ideally would like to modify the class above to something along the lines of
// Inside setter class further above
int get_thing_a()
{
return perform_action<THINGA>(...);
}
int get_thing_b()
{
return perform_action<THINGB>(...);
}
The answer is, maybe I can't, and I need to pass int the shared_ptr as a parameter and call the specific methods I need instead of trying to tie a shared_ptr method to a static function (in hindsight, that doesn't sound like a good idea...but I wanted to bounce my idea)
Whoever makes the actual call will need a reference of the object, one way or the other. Therefore, assuming you want perform_action to perform the actual call, you will have to pass the parameter.
Now, if you really want to store which function of Base to call as a static in thing_traits without passing a parameter, you can leverage pointer to member functions:
template <>
struct thing_traits<THINGA>
{
static constexpr int (Base::*first_function)() = &Base::get_thing_one;
...
}
template < thing_select T, typename TT = thing_traits<T>>
int perform_action(Base & b)
{
return (b.*TT::first_function)() + ...;
}
You can also play instead with returning a function object that does the call for you (and the inner function takes the parameter).
It all depends on who you need to make the call and what information/dependencies you assume you have available in each class/template.
Given the following template in a header file, and a couple of specializations:
template<typename> class A {
static const int value;
};
template<> const int A<int>::value = 1;
template<> const int A<long>::value = 2;
and building with clang-5, it results in errors for each source unit that included the file, all complaining about multiple definitions for A<int>::value and A<long>::value.
At first, I thought that maybe the template specializations needed to be put in a specific translation unit, but on checking the spec, this apparently should be allowed, because the value is a constant integer.
Am I doing something else wrong?
EDIT: if I move the definition into a single translation unit, then I can no longer use the value of A<T>::value in the context of a const int (eg, where its value is being used to calculate the value of another const assignment) , so the value really needs to be in a header.
In c++11 you maybe can go that way:
template<typename> class B {
public:
static const int value = 1;
};
template<> class B<long> {
public:
static const int value = 2;
};
template<typename T> const int B<T>::value;
If you only want to specialize the value var, you can use CRTP for that.
From C++17 you can make your definition inline:
template<> inline const int A<int>::value = 1;
template<> inline const int A<long>::value = 2;
Also from c++17 you can remove the 'template const int B::value;' for constexpr:
template<typename> class C {
public:
static constexpr int value = 1;
};
template<> class C<long> {
public:
static constexpr int value = 2;
};
// no need anymore for: template<typename T> const int C<T>::value;
And another solution for c++11 can be to use a inline method instead of inline vars which are allowed from c++17:
template<typename T> class D {
public:
static constexpr int GetVal() { return 0; }
static const int value = GetVal();
};
template <> inline constexpr int D<int>::GetVal() { return 1; }
template <> inline constexpr int D<long>::GetVal() { return 2; }
template< typename T>
const int D<T>::value;
In addition to your last edit:
To use your values also in other dependent definitions it seems to be the most readable version if you use the inline constexpr methods.
Edit: "Special" version for clang, because as OP tells us, clang complains with "specialization happening after instantiation". I don't know if clang or gcc is wrong in that place...
template<typename T> class D {
public:
static constexpr int GetVal();
static const int value;
};
template <> inline constexpr int D<int>::GetVal() { return 1; }
template <> inline constexpr int D<long>::GetVal() { return 2; }
template <typename T> const int D<T>::value = D<T>::GetVal();
int main()
{
std::cout << D<int>::value << std::endl;
std::cout << D<long>::value << std::endl;
}
I told already that CRTP is possible if not the complete class should be redefined. I checked the code on clang and it compiles without any warning or error, because OP comments that he did not understand how to use it:
template<typename> class E_Impl {
public:
static const int value = 1;
};
template<> class E_Impl<long> {
public:
static const int value = 2;
};
template<typename T> const int E_Impl<T>::value;
template < typename T>
class E : public E_Impl<T>
{
// rest of class definition goes here and must not specialized
// and the values can be used here!
public:
void Check()
{
std::cout << this->value << std::endl;
}
};
int main()
{
E<long>().Check();
std::cout << E<long>::value << std::endl;
E<int>().Check();
std::cout << E<int>::value << std::endl;
}
Suppose I have class A and two derived classes, B and C, e.g.:
#include <iostream>
#include <list>
#include <string>
using namespace std;
class A {
public:
virtual void poke() const = 0;
virtual ~A() {};
};
class B : public A {
string _response;
public:
B(const string& response) : _response(response) {}
void poke () const {
cout << _response << endl;
}
};
class C : public A {
string _response;
public:
C(const string& response) : _response(response) {}
void poke () const {
cout << "Well, " << _response << endl;
}
};
Can I somehow initialize an std::list using the following initializer list: {B("Me"), C("and you")}, so that polymorphism works when I iterate over the list and call poke() (i.e., no slicing occurs)? I guess I need to define an std::list<Smth>, where Smth accepts temporary objects, has a copy constructor that does move semantics inside (because initialization lists seem to be doing copying and not moving), and supports smart pointers so I can iterate with it and do (*it)->poke(). Just for clarity, I want to be be able to write:
list<Smth> test {B("Me"), C("and you")};
for(auto it = test.begin(); it != test.end(); it++) {
(*it)->poke();
}
I was trying to find a simple solution but I got to the point where my program compiled but generated run time errors, and so I gave up at that point... Maybe somehow make a unique pointer out of a temporary object? Or can I use && somehow?
For polymorphism, you need a reference or a pointer. Both will become dangling as soon as the sentence ends, because even if you bound those objects to them somehow, you bound them to temporary objects.
The usual solution is to dynamically allocate and create the objects and holding them with pointers. This means something like the following (I also changed the loop to C++11 style, instead of using iterators directly):
std::list<std::unique_ptr<A>> test {
std::make_unique<B>("Me"), std::make_unique<C>("and you")};
for(const auto& p : test) {
p->poke();
}
Well, if I am willing to do extra copying of B and C and use a shared_ptr instead of a unique_ptr, then the following example works (I am not saying it is good programming style, but it does show the cost of having a convenient notation with initialization lists):
#include <iostream>
#include <list>
#include <memory>
#include <string>
using namespace std;
class A {
public:
virtual void poke() const = 0;
virtual ~A() {}
};
class B : public A {
string _response;
public:
B(const string& response) : _response(response) {}
void poke () const {
cout << _response << endl;
}
operator shared_ptr<A>() {
return make_shared<B>(*this);
}
};
class C : public A {
string _response;
public:
C(const string& response) : _response(response) {}
void poke () const {
cout << "Well, " << _response << endl;
}
operator shared_ptr<A>() {
return make_shared<C>(*this);
}
};
int main() {
list<shared_ptr<A>> test {B("Me"), C("and you")};
for(const auto& it : test) {
it->poke();
}
}