Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a member in a primary class template not declared in the scope of the specialized class?

Tags:

c++

Please be aware that you will see an oversimplified version of the code here. So it might look useless. However, that is not the problem.

The problem is that I have a primary template class like this:

// The primary template class
template<int N>
struct Start {
  int start;

  template<typename... Args>
  int operator()(Args... args) const {return start;}
};

When I specialize this class template:

// Specialization for N=1:
template<>
struct Start<1> {
  int operator()(int i) const {return start;}
};

I get the following error:

error: ‘start’ was not declared in this scope
int operator()(int i) const {return start;}

Why is start not declared in the scope of class Start<1>?

Question

  • Why does the specialized class not recognize the member of the primary class?

I appreciate any suggestions.

like image 888
Ali Avatar asked Mar 06 '20 12:03

Ali


People also ask

What is the difference between class template and template class?

An individual class defines how a group of objects can be constructed, while a class template defines how a group of classes can be generated. Note the distinction between the terms class template and template class: Class template. is a template used to generate template classes.

How would you define member function outside the class template?

Member functions of class templates (C++ only) You may define a template member function outside of its class template definition. The overloaded addition operator has been defined outside of class X . The statement a + 'z' is equivalent to a. operator+('z') .

What is meant by template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

What does template <> mean in C++?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.


1 Answers

Template specialization is not the same as inheritance.

Your specialization is a completely different type from the primary template. No data members or functions are shared.

If you want to share a common member, then make both types inherit from a common base class.

like image 167
Bathsheba Avatar answered Nov 14 '22 10:11

Bathsheba