Question

I'm using g++ for compiling my C++ program, but I want to stop the implicit conversion between type like int and dooble for example: I have a function that use a double as parameter, but when I send in this function's parameter an int, the compilation pass without error or warning.

so that is my question, how to stop the implicit conversions??

thanks.

Was it helpful?

Solution

You cannot avoid implicit conversion from lower to higher type. However you can do vice-versa if your compiler supports C++0x.

void func(int x){}

int main()
{
   func({2.3}); // error: narrowing
}

OTHER TIPS

You could try this:

#include <iostream>

template<typename T>
void func(T t);

void func(double d)
{
    std::cout << "D:" << d << "\n";
}


int main()
{
    func(2.3);   // OK
    func(2);     // Fails at compile time.
}

I think Martin's answer is the way to go. It can find the conversion at link time. If you have to find at compile time, you can add static_assert or a similar one to the function template:

template<typename T>
void func( T ) {
  //static_assert( sizeof( T ) == 0, "..." ); // if you can use static_assert
  int a[ (sizeof( T ) == 0) ? 1 : -1 ];
}

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top