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?
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");
...
};