Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit int type as parameter

Is it possible to write a function as:

void func(uint64_t val) {template <typename T>

void call_with(std::function<void(T)> f, T val) { f(val); }

int main() { auto print = [](int x) { std::cout << x; }; call_with(print, 42); }}

where a compile time error is generated if it's called with any other integer type than uint64_t, without modifying my #pragma warnings?

ie:

uint32_t x = 0;
func(x) {…} // Error!
func(uint64_t(x)) {…} // Succes!
like image 799
Viktor Sehr Avatar asked Apr 11 '26 08:04

Viktor Sehr


2 Answers

Overload the function with a function template. The function template will be a better match for all argument types except uint64_t. You can define the function template, so that it will create an error if used.

void func(uint64_t val) { ... }

template <typename T>
void func(T)
{
    static_assert(false, "argument type is not uint64_t");
}

With C++11 you can use the following template:

template <typename T>
void func(T&&) = delete;
like image 123
nosid Avatar answered Apr 12 '26 21:04

nosid


This would work:

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

template<>
void func<uint64_t>( uint64_t param )
{
}

You'll get a linker error (close enough). Sample: http://ideone.com/5ft4F

like image 36
Luchian Grigore Avatar answered Apr 12 '26 21:04

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!