g++ compiler and implicit conversion
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: 开发者_JS百科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.
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.
}
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
}
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.
精彩评论