patchwork
patchwork

Reputation: 1221

How can I prevent implicit conversion from char to int?

I have the following code:

#include <iostream>

template<typename T> class DynArray 
{ 
  T *contents; 
  int size; 
public: 
  explicit DynArray(int initial_size); 
}; 

int main() 
{ 

  DynArray<std::string> b('7'); 

  return 0; 
}

My question is: how can I prevent the implicit conversion from char to int from compiling? (i.e. this line: `DynArray b('7');

Upvotes: 1

Views: 870

Answers (1)

David
David

Reputation: 28178

You can't directly, but you can make an overload of the constructor which gets chosen first when passed a char...

explicit DynArray(char);

Make it private and don't define it, just declare it. The same as declaring but not defining a copy ctor/copy assignment operator to prevent a class from being copyable.

Or, with C++11, make it deleted (which is the new cleaner/clearer/better way of doing the above)...

explicit DynArray(char) = delete;

Upvotes: 6

Related Questions