Prevent int casting when calling a function

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*what I want.

Can I get some similar errors when trying to cause foo(a)?

+4
source share
3 answers

As a workaround, you can overload foo with the remote version:

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

As a more general solution, you can create a remote 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) {}

, clang 3.8, clang 3.9 gcc 6.2.

+7

static_assert:

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

, :

template<typename>
void foo(T);

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

template<>
void foo(int64_t x) {
    // ...
}
+3

void foo(int64_t& x)

, int32_t const const int64_t, .

, foo , . , foo, .

, , . foo((int64_t)1);

+1

Source: https://habr.com/ru/post/1664254/


All Articles