Can all instances of a class template use the same template independent member function?

In the example below, I am assuming that there will be two different instances of the class template function get_count()

, which is redundant since they are independent of the template parameter. Is this true (or is it optimized?) And is there a way to force all instances of the template to share a common function (perhaps the template argument template, for example <*>

?) When it comes to some member functions?

template<class T>
class A {
    private:
        T obj;
        int count;
    public:
        int get_count(); 
};

template<class T>
int A<T>::get_count() { // This function doesn't really need to
                        // depend on the template parameter.
    return this->count;
}

int main() {
    A<int> a;  //<--First template instantiation
    A<bool> b; //<--Second template instantiation
    int i = a.get_count(); //<--Could theoretically use the same code
    int j = b.get_count(); //<--
    return 0;
}

      

Also, what if the member variables are reordered?

+3


source to share


2 answers


You are wrong in your assumption that all instances can use the same code for A<..>::get_count()

.

Look at the members of the class:

    T obj;
    int count;

      

Thus, the tamplate argument T

specifies the offset count

that the member returns get_count()

.



In any case, if two instances are executed to execute the same instructions, nothing prevents the compiler from combining them.
As a QoI problem, it should if optimization is enabled.

There is a way to force multiple classes to use the same code for a function without relying on compiler optimizations:
Derived from a common base providing the function.

struct A_base {
    int get_count();
protected:
    int count;
}
template<class T>
class A : A_base {
    T obj;
};

int A_base::get_count() {
    return this->count;
}

      

(Ultimately, however, the correct as-if rule is: β€’ The compiler may duplicate code to expose optimization opportunities not otherwise used.)

+3


source


Yes, there is a way, and the implementation method is used:

Create a base class that is template parameter independent and puts template independent code there. This will only make an instance once. For code that depends on template parameters, do this in the template itself:



class base {
   int count;
public:
    std::size_t get_count()...
};

template <class T>
class derived : public base {};

      

Techniques like this are used to reduce code bloat in implementations.

0


source







All Articles