Carlos Miguel Colanta
Carlos Miguel Colanta

Reputation: 2823

Pointer by reference on templates and normal functions

Here is my code :

#include <iostream>


template<typename B>
class test{
    public:
    B* t;

    test(const B& init){
    }   
};



void funct(const int*& test){

}


int main(int argc, char** argv) {

    test<int*> t(new int(2));   // works fine
    funct(new int(2));          //error

    return 0;
}

I am trying to emulate what's happening on my templated class, but somehow i get errors. I believe that const B& init with B as int* will be const int*& init. Adding const allowed it to accept temporary "new"s. I made a non-templated function to test it and it has this header, void funct(const int*& test). It is just the same as above but how come it wont take new int(2) ?

Upvotes: 1

Views: 43

Answers (1)

juanchopanza
juanchopanza

Reputation: 227418

const int*& means "reference to pointer to const int. You need the const to apply to the pointer, not to the int:

void funct(int* const& test){}

This is what the template version does. T is a pointer to int, so T& is really a reference to pointer to int. The template does not perform a textual substitution of T for int*. It substitutes the type. You'd get the same if you used typedef int* X and const X&.

Upvotes: 4

Related Questions