using inherited member in class template

hi everyone,
i would like to use a template class and want to work with a member variable from a common parent class from within a template function:
struct X
{
int target = 0;
};

struct Y : X
{};

struct Z : X
{};

template<typename T>
struct A
{
int getTarget(){ return T.target; } // is this possible somehow?!
};

int main()
{
A<Y> a1;
A<Z> a2;
}

can i tell the template class that all T inherit from X?
can i tell the template class that all T inherit from X?

You might be able to do something like that when concepts (http://en.cppreference.com/w/cpp/language/constraints) has been added to C++. It might have been able to give you better error messages but it shouldn't' be necessary for it to work correctly.

The problem with T.target is that . (dot) is used to access something from an object but T is not an object. Which object do you want to access target from?
maybe i should show my actual code, not the abstract minimum:
1
2
3
4
5
6
7
8
9
10
11
12
template<class T>
class PageContainingBundleImages {
public:

	void addBundleImage(libdf::DBundle *bnd) {
		getBundleImages()->push_back(new T(bnd));
	}

	std::vector<T*>*getBundleImages() { return &bundleImages; }
protected:
	std::vector<T*>bundleImages;
};


All T are X and i want to use X::target from within the template class. but the template class knows nothing about X, can i change that?
You don't need to tell that T inherits from X. Just write the code with that assumption in mind and it should work as long as the code is correct.

If you are worried that the code will accidentally "work" when an incorrect type is used, or if you just want to give a more user-friendly error message, you could use a static_assert.

1
2
3
4
5
6
template<class T>
class PageContainingBundleImages {
	static_assert(std::is_convertible_v<T&, X&>, 
		"PageContainingBundleImages<T>: X must be a public base class of T");
	...
};
Last edited on
okay, wow, i would not have thought that it works "just like this" without defining it. nice, thank you!
Topic archived. No new replies allowed.