user52291
user52291

Reputation: 171

Passing const reference to Template Class that uses custom objects

I have a template class I'm creating that takes in custom objects. It looks a little something like this.

template<typename T1,typename T2>
class myClass
{
public:
    myClass(const T1 &param1, const T2 &param2);
}



template<typename T1, typename T2>
myClass<T1,T2>::
myClass
(const T1 &param1, const T2 &param2)
{
    T1.customFunction(); //doesn't compile
}

So I expect that anytime this template class is used the person who uses it is responsible for making sure the class T1 has a function called customFunction(). Fair enough, the problem is customFunction must be guaranteed to be const at compile time since it's being called on a constant paramater (param1), but how can this even be possible if T1 is essentially a dummy class?

Upvotes: 2

Views: 126

Answers (2)

nikolas
nikolas

Reputation: 8975

You have got it slightly off: not the function must be "const at compile time", but the types that are passed must be known. The reason it does not compile is because you try to call customFunction on the type T1 rather than on an instance of it.

template<typename T1, typename T2>
myClass<T1,T2>::
myClass
(const T1 &param1, const T2 &param2)
{
      param1.customFunction(); //does compile
};

Upvotes: 0

Bo Persson
Bo Persson

Reputation: 92211

First, it should be

param1.customFunction();

because you call it with the parameter object, not the type.

Secondly, you don't have to worry. Whenever you construct a myClass object, the compiler will check that the parameters you pass are of types where the member function is present and callable.

Upvotes: 1

Related Questions