3
votes

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!
2
So, you want to prevent func(1)? - Pete Becker
This seems like an unusual requirement; passing a smaller integer type causes no loss of precision or data and is very well-defined. For passing by value, it's making a copy, so there's no modification issues. What is your reason behind requiring exactly the same bit width? - ssube
@peachykeen I've got two id's which handles a caching mechanism, whereas one happen to be 32bit and one 64bit. In this case, it'd be conveniant to get a compilation error if the 32bit id is passed to the 64bit parameter. (I am aware I can make explicit types.) - Viktor Sehr

2 Answers

5
votes

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;
4
votes

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