deduce of argument of type class method (overloads by const qualifier) fails with trailing return type in gcc, but not in clang - c++

Nothing clearer than an old good MCVE:
struct X {
auto get(int) const -> int { return {}; }
auto get(int) -> int { return {}; }
};
template <class R> auto f(auto (X::*)(int) const -> R) {}
// ^~~~ ~~~~
// trailing return type
int main() {
f(&X::get);
}
This fails in g++ (4.9.2 & 5.1.0). However if the old return type is used:
template <class R> auto f(R (X::*)(int) const) {}
// ^
// old return type
it works.
On clang (3.5.0) both variants work.
I know that trailing return type changes when the return type is inferred and the scope of it, so I wouldn't be quick to cast it as a gcc bug. So what does the standard says? Which compiler is right?
The most significant message in the error I think is
couldn't deduce template parameter ‘R’`
g++ full message:
main2.cpp: In function ‘int main()’:
main2.cpp:21:12: error: no matching function for call to ‘f(<unresolved overloaded function type>)’
f(&X::get);
^
main2.cpp:18:25: note: candidate: template<class R, class auto:1> auto f(auto:1 (X::*)(int) const)
template <class R> auto f(auto (X::*)(int) const -> R) {}
^
main2.cpp:18:25: note: template argument deduction/substitution failed:
main2.cpp:21:12: note: types ‘auto:1 (X::)(int) const’ and ‘int (X::)(int)’ have incompatible cv-qualifiers
f(&X::get);
^
main2.cpp:21:12: note: couldn't deduce template parameter ‘R’
<builtin>: recipe for target 'main2' failed
make: *** [main2] Error 1

As pointed in the question this is a gcc bug which was beed fixed in version 6
gcc.gnu.org/bugzilla/show_bug.cgi?id=69139

Related

"no matching function for call to" when having a function pointer with template arguments as a template argument

I'm writing a template wrapper function that can be applied to a functions with different number/types of arguments.
I have some code that works but I'm trying to change more arguments into template parameters.
The working code:
#include <iostream>
int func0(bool b) { return b ? 1 : 2; }
//There is a few more funcX...
template<typename ...ARGS>
int wrapper(int (*func)(ARGS...), ARGS... args) { return (*func)(args...) * 10; }
int wrappedFunc0(bool b) { return wrapper<bool>(func0, b); }
int main()
{
std::cout << wrappedFunc0(true) << std::endl;
return 0;
}
Now I want int (*func)(ARGS...) to also be a template parameter. (It's for performance reasons. I want the pointer to be backed into the wrapper, because the way I'm using it prevents the compiler from optimizing it out.)
Here is what I came up with (The only difference is I've changed the one argument into a template parameter.):
#include <iostream>
int func0(bool b) { return b ? 1 : 2; }
//There is a few more funcX...
template<typename ...ARGS, int (*FUNC)(ARGS...)>
int wrapper(ARGS... args) { return (*FUNC)(args...) * 10; }
int wrappedFunc0(bool b) { return wrapper<bool, func0>(b); }
int main()
{
std::cout << wrappedFunc0(true) << std::endl;
return 0;
}
This doesn't compile. It shows:
<source>: In function 'int wrappedFunc0(bool)':
<source>:9:55: error: no matching function for call to 'wrapper<bool, func0>(bool&)'
9 | int wrappedFunc0(bool b) { return wrapper<bool, func0>(b); }
| ~~~~~~~~~~~~~~~~~~~~^~~
<source>:7:5: note: candidate: 'template<class ... ARGS, int (* FUNC)(ARGS ...)> int wrapper(ARGS ...)'
7 | int wrapper(ARGS... args) { return (*FUNC)(args...) * 10; }
| ^~~~~~~
<source>:7:5: note: template argument deduction/substitution failed:
<source>:9:55: error: type/value mismatch at argument 1 in template parameter list for 'template<class ... ARGS, int (* FUNC)(ARGS ...)> int wrapper(ARGS ...)'
9 | int wrappedFunc0(bool b) { return wrapper<bool, func0>(b); }
| ~~~~~~~~~~~~~~~~~~~~^~~
<source>:9:55: note: expected a type, got 'func0'
ASM generation compiler returned: 1
<source>: In function 'int wrappedFunc0(bool)':
<source>:9:55: error: no matching function for call to 'wrapper<bool, func0>(bool&)'
9 | int wrappedFunc0(bool b) { return wrapper<bool, func0>(b); }
| ~~~~~~~~~~~~~~~~~~~~^~~
<source>:7:5: note: candidate: 'template<class ... ARGS, int (* FUNC)(ARGS ...)> int wrapper(ARGS ...)'
7 | int wrapper(ARGS... args) { return (*FUNC)(args...) * 10; }
| ^~~~~~~
<source>:7:5: note: template argument deduction/substitution failed:
<source>:9:55: error: type/value mismatch at argument 1 in template parameter list for 'template<class ... ARGS, int (* FUNC)(ARGS ...)> int wrapper(ARGS ...)'
9 | int wrappedFunc0(bool b) { return wrapper<bool, func0>(b); }
| ~~~~~~~~~~~~~~~~~~~~^~~
<source>:9:55: note: expected a type, got 'func0'
Execution build compiler returned: 1
(link to the compiler explorer)
It looks like a problem with the compiler to me, but GCC and Clang agree on it so maybe it isn't.
Anyway, how can I make this template compile correctly with templated pointer to a function?
EDIT:
Addressing the duplicate flag Compilation issue with instantiating function template
I think the core of the problem in that question is the same as in mine, however, it lacks a solution that allows passing the pointer to function (not only its type) as a template parameter.
This doesn't work because a pack parameter (the one including ...) consumes all remaining arguments. All arguments following it can't be specified explicitly and must be deduced.
Normally you write such wrappers like this:
template <typename F, typename ...P>
int wrapper(F &&func, P &&... params)
{
return std::forward<F>(func)(std::forward<P>(params)...) * 10;
}
(And if the function is called more than once inside of the wrapper, all calls except the last can't use std::forward.)
This will pass the function by reference, which should be exactly the same as using a function pointer, but I have no reasons to believe that it would stop the compiler from optimizing it.
You can force the function to be encoded in the template argument by passing std::integral_constant<decltype(&func0), func0>{} instead of func0, but again, I don't think it's going to change anything.
The 2nd snippet is not valid because:
a type parameter pack cannot be expanded in its own parameter clause.
As from [temp.param]/17:
If a template-parameter is a type-parameter with an ellipsis prior to its optional identifier or is a parameter-declaration that declares a pack ([dcl.fct]), then the template-parameter is a template parameter pack. A template parameter pack that is a parameter-declaration whose type contains one or more unexpanded packs is a pack expansion. ... A template parameter pack that is a pack expansion shall not expand a template parameter pack declared in the same template-parameter-list.
So consider the following invalid example:
template<typename... Ts, Ts... vals> struct mytuple {}; //invalid
The above example is invalid because the template type parameter pack Ts cannot be expanded in its own parameter list.
For the same reason, your code example is invalid. For example, a simplified version of your 2nd snippet doesn't compile in msvc.

How do you declare a generic type of an expression in a `requires` constraint?

I may be asking a wrong question here, but what exactly am I doing wrong that it causes the compiler to think that the constraint I'm expecting on pop method of the stack is std::same_as<void, T>?
#include <concepts>
#include <stack>
template <typename S, typename T>
concept generic_stack = requires(S s, T t) {
s.push(t);
{ s.pop() } -> std::same_as<T>; // error seems to stem from here
};
template <typename T, generic_stack<T> S>
void compile_if_stack(S) {}
int main() {
compile_if_stack<int>(std::stack<int>{});
}
I tried std::same_as<decltype(s.pop()), T>; and it appears to work, but what I don't understand is what's wrong with the former approach.
Full error
# clang 12.0.1
$ clang++ -std=c++20 main.cpp
main.cpp:14:5: error: no matching function for call to 'compile_if_stack'
compile_if_stack<int>(std::stack<int>{});
^~~~~~~~~~~~~~~~~~~~~
main.cpp:11:6: note: candidate template ignored: constraints not satisfied [with T = int, S = std::stack<int>]
void compile_if_stack(S) {}
^
main.cpp:10:23: note: because 'generic_stack<std::stack<int>, int>' evaluated to false
template <typename T, generic_stack<T> S>
^
main.cpp:7:25: note: because type constraint 'std::same_as<void, int>' was not satisfied:
{ s.pop() } -> std::same_as<T>; // error seems to stem from here
^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/11.1.0/../../../../include/c++/11.1.0/concepts:63:19: note: because '__detail::__same_as<void, int>' evaluated to false
= __detail::__same_as<_Tp, _Up> && __detail::__same_as<_Up, _Tp>;
^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/11.1.0/../../../../include/c++/11.1.0/concepts:57:27: note: because 'std::is_same_v<void, int>' evaluated to false
concept __same_as = std::is_same_v<_Tp, _Up>;
^
1 error generated.
C++ compiler from GCC 11.1.0 comes up with semantically identical error message.
This is because stack.pop() returns void, as per documented in std::stack::pop.
The constraint is not right, you should check for top instead:
template <typename S, typename T>
concept generic_stack = requires(S s, T t) {
s.push(t);
{ s.top() } -> std::same_as<T const&>;
};
std::stack does not return a value on pop. It has a separate function for that. Namely, top. So pop() is a void function. Hence the error.

Why can't this parameter pack accept function pointers?

I'm trying to create a parameter pack full of function pointers, but GCC (with c++17 standard) generates a deduction failed error. Why is that?
As written here:
For pointers to functions, the valid arguments are pointers to functions with linkage (or constant expressions that evaluate to null pointer values).
In my example, that's the case (isn't it?).
Is this rule invalidated for parameter packs? Did I miss something in the standard? If that's the case, how can I fix my code, without passing the function pointers as function arguments (ie without declaring T run2(T input, Funcs... funcs).
// In f.hpp
template<typename T>
T run2(T input)
{
return input;
}
template<typename T, T(*f)(T), class ... Funcs>
T run2(T input)
{
return run2<T, Funcs...>(f(input));
}
// In m.cpp
unsigned add2(unsigned v)
{
return v+2;
}
int main()
{
unsigned a=1;
a = run2<unsigned, add2>(a); // works
a = run2<unsigned, add2, add2>(a); // doesn't work
std::cout << a << std::endl;
return 0;
}
This the error I get with run2<unsigned, add2, add2> (GCC doesn't tell me why the last attempt actually failed):
m.cpp: In function ‘int main()’:
m.cpp:37:37: error: no matching function for call to ‘run2(unsigned int&)’
a = run2<unsigned, add2, add2>(a);
^
In file included from m.cpp:2:0:
./f.hpp:85:3: note: candidate: template<class T> T run2(T)
T run2(T input)
^
./f.hpp:85:3: note: template argument deduction/substitution failed:
m.cpp:37:37: error: wrong number of template arguments (3, should be 1)
a = run2<unsigned, add2, add2>(a);
^
In file included from m.cpp:2:0:
./f.hpp:109:3: note: candidate: template<class T, T (* f)(T), class ... Funcs> T run2(T)
T run2(T input)
^
./f.hpp:109:3: note: template argument deduction/substitution failed:
You declared a type parameter pack, class... Funcs. You can't pass function pointers as arguments for type parameters, because they are values, not types. Instead, you need to declare the run2 template so that it has a function pointer template parameter pack. The syntax to do so is as follows:
template<typename T, T(*f)(T), T(*...fs)(T)>
T run2(T input)
{
return run2<T, fs...>(f(input));
}
(The rule is that the ... is part of the declarator-id and goes right before the identifier, namely fs.)
The pack fs can accept one or more function pointers of type T (*)(T).

auto-returning functions and template instantiation

While writing some template code, I ran into <unresolved overloaded function type> errors which can be reduced to the following.
template <int N>
auto bar()
{
return N;
}
int main(int, char* [])
{
auto foo = [] (auto func) {
return func();
};
foo(bar<3>);
}
With the errors being:
unresolved_overload.cpp: In function 'int main(int, char**)':
unresolved_overload.cpp:26:28: error: no match for call to '(main(int, char**)::<lambda(auto:1)>) (<unresolved overloaded function type>)'
std::cout << foo(bar<3>) << std::endl;
^
unresolved_overload.cpp:21:29: note: candidate: template<class auto:1> constexpr main(int, char**)::<lambda(auto:1)>::operator decltype (((const main(int, char**)::<lambda(auto:1)>*)((const main(int, char**)::<lambda(auto:1)>* const)0))->operator()(static_cast<auto:1&&>(<anonymous>))) (*)(auto:1)() const
auto foo = [] (auto func) {
^
unresolved_overload.cpp:21:29: note: template argument deduction/substitution failed:
unresolved_overload.cpp:26:28: note: couldn't deduce template parameter 'auto:1'
std::cout << foo(bar<3>) << std::endl;
^
unresolved_overload.cpp:21:29: note: candidate: template<class auto:1> main(int, char**)::<lambda(auto:1)>
auto foo = [] (auto func) {
^
unresolved_overload.cpp:21:29: note: template argument deduction/substitution failed:
unresolved_overload.cpp:26:28: note: couldn't deduce template parameter 'auto:1'
std::cout << foo(bar<3>) << std::endl;
If we replace the auto-return with the explicit return type, int, the example will compile fine.
Why does auto-return run into these issues? I looked into template argument deduction and substitution but the search was largely unfruitful. I thought it might have something to do with the order of template instantiation / etc but couldn't make too much sense of it...
Per AndyG's suggestion, I found the same issue on GCC's bug list. Bug 64194. First reported in 2014. Thus the conclusion seems to be that this is a GCC bug and thankfully not another special case for templates.
Working around this just requires having something else to trigger the instantiation (e.g. assign to a variable, a using declaration).
Try this:
template <typename func>
auto bar(func&& f)->decltype(f())
{
return f();
}
int main()
{
int i = 100;
auto f = [=]()
{
return i;
};
bar(f);
return 0;
}

How do I implement "perfect forwarding" in a class template?

I have a class template with template parameter T and a member of type T. I want to initialize that member with a parameter passed to the ctor and I also want the passed parameter to be moved if it's a rvalue reference and if T supports move semantic:
template <typename T>
class C {
public:
explicit C(T t) : t_(t)
{
}
explicit C(T&& t) : t_(std::move(t))
{
}
...
private:
T t_;
};
g++ 4.8 gives the following error if I try to pass rvalue reference to the ctor:
int main()
{
int x = 0;
C<int> p1{x}; // OK
C<int> p2{1}; // error g++-4.8: call of overloaded ‘C(<brace-enclosed initializer list>)’ is ambiguous
return 0;
}
The full error text:
g++-4.8 -std=c++11 -O2 -Wall -pedantic -pthread main.cpp
main.cpp: In function ‘int main()’:
main.cpp:23:16: error: call of overloaded ‘C()’ is ambiguous
C p2{1}; // error g++-4.8: call of overloaded ‘C()’ is ambiguous
^
main.cpp:23:16: note: candidates are:
main.cpp:12:11: note: C::C(T&&) [with T = int]
explicit C(T&& t) : t_(std::move(t))
^
main.cpp:8:14: note: C::C(T) [with T = int]
explicit C(T t) : t_(t)
^
main.cpp:6:7: note: constexpr C::C(const C&)
class C {
^
main.cpp:6:7: note: constexpr C::C(C&&)
Could someone help me, please?
Thanks!
I solved the problem by making the parameter t in C(T t) const reference.