The snippet of code compiled with std=c++17
as the only compiler flag ...
- ... compiles successfully with GCC 9.1. Godbolt
- ... issues a compiler error with Clang 8.0.0 (error below snippet). Godbolt
Question: is this a bug in the Clang compiler or is GCC wrong to accept this code or is something else at play?
#include <functional>
#include <tuple>
template <typename... Ts>
struct Foo
{
template <typename T>
using Int = int;
// Function that accepts as many 'int' as there are template parameters
using Function = std::function< void(Int<Ts>...) >;
// Tuple of as many 'int' as there are template parameters
using Tuple = std::tuple< Int<Ts>... >;
auto bar(Function f)
{
std::apply(f, Tuple{}); // Error with Clang 8.0.0
}
};
int main()
{
auto foo = Foo<char, bool, double>{};
foo.bar([](int, int, int){});
}
What strikes me as odd is that Clang's error indicates it successfully aliased Tuple
as std::tuple<int, int, int>
but it wrongly aliases Function
as just std::function<void(int)>
, with only one instead of three arguments.
In file included from <source>:2:
In file included from /opt/compiler-explorer/gcc-8.3.0/lib/gcc/x86_64-linux-gnu/8.3.0/../../../../include/c++/8.3.0/functional:54:
/opt/compiler-explorer/gcc-8.3.0/lib/gcc/x86_64-linux-gnu/8.3.0/../../../../include/c++/8.3.0/tuple:1678:14: error: no matching function for call to '__invoke'
return std::__invoke(std::forward<_Fn>(__f),
^~~~~~~~~~~~~
/opt/compiler-explorer/gcc-8.3.0/lib/gcc/x86_64-linux-gnu/8.3.0/../../../../include/c++/8.3.0/tuple:1687:19: note: in instantiation of function template specialization 'std::__apply_impl<std::function<void (int)> &, std::tuple<int, int, int>, 0, 1, 2>' requested here
return std::__apply_impl(std::forward<_Fn>(__f),
^
<source>:19:14: note: in instantiation of function template specialization 'std::apply<std::function<void (int)> &, std::tuple<int, int, int> >' requested here
std::apply(f, Tuple{}); // Error
^
<source>:26:9: note: in instantiation of member function 'Foo<char, bool, double>::bar' requested here
foo.bar([](int, int, int){});
Additional Research
As other users in the comments already pointed out, making the Int
template alias dependent on the type T
fixes the issue:
template <typename T>
using Int = std::conditional_t<true, int, T>;
Something else I found out, just referring to the Function
type from the outside also makes it work as expected/desired:
int main()
{
auto f = Foo<char, bool, double>::Function{};
f = [](int, int, int){};
}