Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent casting of int when calling function

Tags:

c++

casting

c++11

I have the following code:

void foo(int64_t x) {}
void bar(int64_t* x) {}

int main() {
    int32_t a = 3;
    foo(a);
    bar(&a);
}

When I try to compile this, it gives an error that cannot convert int32_t* to int64_t*, which is what I want.

Is it possible to get some similar errors when I try to invoke foo(a) ?

like image 707
bbvan Avatar asked Dec 18 '22 11:12

bbvan


2 Answers

As a workaround you can overload foo with the deleted version:

void foo(int32_t x) = delete;
void foo(int64_t x) {}

As a more general solution you may create a deleted function template and then specialize it for int64_t (thanks to @Someprogrammerdude):

template<typename T>
void foo(T) = delete;

template<>
void foo(int64_t x) {}

Interestingly, it doesn't compile with clang 3.8, but compiles fine with clang 3.9 and gcc 6.2.

like image 161
Edgar Rokjān Avatar answered Dec 24 '22 01:12

Edgar Rokjān


You can use a template and a static_assert:

template<typename T>
void foo(T x) {
    static_assert(std::is_same<int64_t, T>::value, "!");
    // ...
}

Or a full specialization, where the primary template isn't defined or is deleted:

template<typename>
void foo(T);

// This should be fine as well
//
// template<typename>
// void foo(T) = delete;

template<>
void foo(int64_t x) {
    // ...
}
like image 34
skypjack Avatar answered Dec 24 '22 01:12

skypjack