Why does the declaration `void(*pf)(int) = bar;` fires the `static_assert` in the snippet below?

c++, c++11, templates

Solution

The behavior is quite straightforward. `T` is being deduced as `int` from the function pointer type below, hence the `static_assert` fails.

void(*pf)(int) = bar; // [T = int]

if I replace `bar` by `bar<const int>` in this declaration the code compiles

That's because you've now explicitly specified that `T` is `const int`, and it's no longer being deduced as `int`.

void(*pf)(int) = bar<const int>; // [T = const int]

You're still allowed to create a function pointer of type `void(*)(int)` to the function `void(const int)` because top level `const`s are not part of the function signature.

Adding `const` to the function pointer type doesn't help because of the same reason, the top level `const` in the function argument type is discarded before `T` is deduced, and it results in the same behavior as the first example.

void(*pf)(const int) = bar;  // [T = int]

Problem

This is a continuation of my prior question. Note that the declaration `void (*pf)(int) = bar;` fires the `static_assert`. I don't understand why. Note also that if I replace `bar`by `bar<const int>` in this declaration the code compiles. ``` #include <iostream> #include <type_traits> template<typename T> void bar(T t) { static_assert(std::is_same<T, const int>::value, "Error!"); std::cout << t << '\n'; } int main() { // static_assert doesn't fire because T==const int bar<const int>(1); // But here static_assert fires because T==int (see the error message). Why is this? // If I replace `bar` by `bar<const int>` below the code compiles. void(*pf)(int) = bar; pf(1000); } ``` Live example

Original source

Related problems