0

I wonder if it is possible to have template class where the member functions can only be called with the exact matching template type? Example:

template<typename T>
   struct testClass {
   void testMethod(T testParam) {};
};


int main() {
    testClass<int> testObject;
    int testInt;
    testObject(testInt);         //ok
    testObject.testMethod(1.1f); //compile error, parameter is not int
}

Basically an adaption for templates from this: How do I avoid implicit conversions on non-constructing functions?, which I am not sure how to achieve.

Thanks

locali
  • 15
  • 3

1 Answers1

1

If you can use at least C++11, you can delete a template method with the same name

template <typename U>
void testMethod (U const &) = delete;

This way, when you call testMethod() with exactly a T value, the not-template method is preferred; when you call testMethod() with a value of different type, the compiler select the template testMethod() but is deleted so give a compilation error.

max66
  • 65,235
  • 10
  • 71
  • 111
  • easy and works. But how does the compiler choose which function to use when both signatures are the same? Where can I find this in the c++ standard? – locali Jan 20 '19 at 18:57
  • when the compiler must choose between a template function and a not-template function, the signatures are different; and the rule is that is preferred the not-template one when is an exact match, the template one otherwise. – max66 Jan 20 '19 at 19:01