wanna ask one question: I have two classes A and B, few data types can only be defined in class B, but A as a higher level class also need use these data types defined in class B. So, I defined a template function in class A, named define_spline(), I can using robot_1 (i.e., class B) class’s pointer to passing the type, but what I want is the class A can have a member object of these types defined in B class (robot_1 struct sp{}). I try to write a template class for whole A, named A2, but I got error ‘rp1 is not a type name’, why this is ok in class A define_spline() function, but not work for class A2 ? and what’s the correct way to do so?
#include<Eigen/Dense>
#include<iostream>
#include <unsupported/Eigen/Splines>
#include <fstream>
#include<memory>
class robot_1
{
private:
static const int nState =9;
static const int nControl =3;
public:
// robot_1(int nx, int nu)
// printf("robot_1 constructor \n");
// }
~robot_1(){}
robot_1()
{
printf("empty robot_1 constructor \n");
}
struct sp
{
using SplineX = Eigen::Spline<double, nState>;
using SplineFittingX = Eigen::SplineFitting<SplineX>;
}sp_;
};
using robotPtr = std::shared_ptr<robot_1>;
class A
{
private:
std::string name = "class_a";
int nState;
int ncontrol;
// Ty::SplineX sp_memeber;
public:
A(){}
~A(){}
template <typename Ty>
void define_spline(const Ty, int a)
{
using SplineX_A = typename Ty::SplineX;
using SplineFittingX_A = typename Ty::SplineFittingX;
SplineX_A spA;
std::cout<<a<<std::endl;
}
robotPtr robotPtr_;
};
template <typename Type2>
class A2
{
private:
Type2::SplineX spx;
Type2::SplineFittingX spxF;
int nState;
int nControl;
public:
A2(){}
~A2(){}
A2(int nx, int nu){
nState = nx;
nControl = nu;
}
};
int main()
{
robotPtr rp1 = std::make_shared<robot_1>();
rp1 ->sp_;
A a;
a.robotPtr_ = std::make_shared<robot_1>();
a.define_spline(rp1->sp_, 6); // here no error
// A2
A2<rp1->sp_> a2(9,3); // error
}
Thanks in advance
>Solution :
A2<rp1->sp_> a2(9,3); // error
Template parameters are always types (until very recently, but this is not material right now). rt1->sp_ is not a type. It is a discrete object. If you look where it appears, struct sp is the type in question. And sp_ is an instance of that type. Types, and objects, are two completely different things, in C++. They are not interchangeable with each other. When something must be a type, it has to be a type, and not an object. When something must be an object it has to be an object, and not a type. Template parameters are types (until very recently, but this is still not material right now).
You might get this to work by using A2<decltype(rp1->sp_)>. The expression decltype(...) resolves to whatever the reference type is. It basically "translates" an object, of some kind, to its type. There are a few rules, and several nuanced rules to decltype(), that your favorite C++ textbook will be happy to explain to you, which is where you can look for more information and examples.