Explicit instantiation for concept checking - c++

We have:
template<typename T>
struct A {
void foo(int a) {
T::foo(a);
}
};
template<typename T>
struct B {
template struct A<T>; // concept check
};
So, I define a concept checker A that checks T by forwarding foo to T::foo.
Now, I want to check whether the argument passed to B satisfies the concept A by explicit instantiation, but the compiler complains that it's the wrong namespace. How can I fix that?

Something like this perhaps:
template<typename T, void(T::*)(int)>
struct A {};
template<typename T>
struct B {
using Check = A<T, &T::foo>;
};
Demo
Or this:
template<typename T>
struct B {
static_assert(
std::is_same<decltype(&T::foo), void(T::*)(int)>::value,
"No T::foo(int) member");
};

So, I found a working example:
#include <tuple>
template<typename A>
struct IA : A {
void foo(int a) {
A::foo(a);
}
void bar(double a) {
A::bar(a);
}
static constexpr auto $ = std::make_tuple(&IA::foo, &IA::bar);
};
template<typename T>
struct B {
// trigger concept/interface check of T "implements" IA
static constexpr auto $ = IA<T>::$;
};
struct Test {
void foo(int a) {}
void bar(int a, int b) {}
};
int main() {
B<Test> b;
b = b;
}
The generation of $ in the structs triggers the compilation. The compiler in the example above correctly complains with:
In instantiation of 'void IA<A>::bar(double) [with A = Test]':
13:57: required from 'constexpr const std::tuple<void (IA<Test>::*)(int), void (IA<Test>::*)(double)> IA<Test>::$'
18:27: recursively required from 'constexpr const std::tuple<void (IA<Test>::*)(int), void (IA<Test>::*)(double)> B<Test>::$'
18:27: required from 'struct B<Test>'
28:13: required from here
10:17: error: no matching function for call to 'IA<Test>::bar(double&)'
10:17: note: candidate is:
24:10: note: void Test::bar(int, int)
24:10: note: candidate expects 2 arguments, 1 provided

Related

How to resolve multiple inheritance ambiguities in C++

I have a small program as follows:
#include <iostream>
template <typename T>
class X{
public:
bool something(){
return true;
}
};
class A: public X<A>{
};
class B: public A, public X<B>{
};
template <typename T>
bool use(T &t)
{
return t.something();
}
int main()
{
B b;
std::cout << "use returned: " << use(b);
}
This will not compile because there is an ambiguity as to which of the two possible versions of something() should be selected:
In instantiation of 'bool use(T&) [with T = B]':
30:43: required from here
22:20: error: request for member 'something' is ambiguous
6:14: note: candidates are: bool X<T>::something() [with T = B]
6:14: note: bool X<T>::something() [with T = A]
In function 'bool use(T&) [with T = B]':
23:1: warning: control reaches end of non-void function [-Wreturn-type]
My question is, how can I resolve this ambiguity if the only place I can edit is the body of use()?
Yes. For example, you can qualify the call to something (godbolt):
template <typename T>
bool use(T &t)
{
return t.A::something();
}
You could add a specialization of the template “use” for the case where T derives from X and then casts to X inside.
template <typename T>
class X{
public:
bool something(){
return true;
}
};
class A: public X<A>{
};
class B: public A, public X<B>{
};
#
# If class derives from X<T> make sure to cast to X<T> before calling something
#
template<typename T>
typename std::enable_if<std::is_base_of<X<T>, T>::value, bool>::type use(T &t)
{
return static_cast<X<T>&>(t).something();
}
#
# This gets run for everything that doesn't derive from X<T>
#
template<typename T>
typename std::enable_if<!std::is_base_of<X<T>, T>::value, bool>::type use(T &t)
{
return t.something();
}
Have to check the syntax though, but this should make sure you get it for your special case while allowing anything with only one “something” call.

Explicitly choose which template overload should be used

Can we chose which function template overload should be used in this case?
struct X { };
struct A { A(X){} };
struct B { B(X){} };
template<class T>
void fun(T, A) { }
template<class T>
void fun(T, B) { }
int main() {
/* explicitly choose overload */ fun(1, X());
}
Error:
error: call of overloaded 'fun(int, X)' is ambiguous
/* explicitly choose overload */ fun(1, X());
^
candidate: void fun(T, A) [with T = int]
void fun(T, A) { }
^~~
candidate: void fun(T, B) [with T = int]
void fun(T, B) { }
^~~
For normal function it looks like this:
void fun(A){}
void fun(B){}
int main() {
((void(*)(A))(fun))(X());
}
Is it possible?
Improving your example, you can try with
((void(*)(int, A))(fun))(1, X());
If you choose not to explicitly specify the first parameter type but still want to specify the second you could go along with lambda dedicated for casting purpose (c++14 solution):
struct X { };
struct A { A(X){} };
struct B { B(X){} };
template<class T>
void fun(T, A) { }
template<class T>
void fun(T, B) { }
int main() {
[](auto v, auto x){ static_cast<void(*)(decltype(v), A)>(fun)(v, x); }(1, X());
}
[live demo]
A low-tech solution to this problem would be to add one extra level of indirection. Add a function like funA, whose sole purpose is to give an explicit name to the first version of fun:
struct X { };
struct A { A(X){} };
struct B { B(X){} };
template<class T>
void fun(T, A) { }
template<class T>
void fun(T, B) { }
template <class T>
void funA(T t, A a) { fun(t, a); }
int main() {
/* explicitly choose overload */ funA(1, X());
}
However, I wonder why you cannot just change the argument to A(X()). You will have to change the calling code anyway, so what's the problem?

template class that derives from same template

I have an equivalent to following code:
struct Empty {
static constexpr int id = 0;
};
template <typename Self, typename Base = Empty> struct Compound : public Base
{
int get_id() const
{
return Self::id;
}
};
struct A : Compound<A>
{
static constexpr int id = 0xa;
};
struct B : Compound<B, A>
{
static constexpr int id = 0xb;
};
template <typename T, typename Base> int get_id(const Compound<T, Base> &c)
{
return c.get_id();
}
int test_a()
{
A var;
return get_id(var);
}
int test_b()
{
B var;
return get_id(var);
}
test_b doesn't compile with following error:
error: no matching function for call to 'get_id(B&)'
return get_id(var);
^
note: candidate: template<class T, class Base> int get_id(const Compound<T, Base>&)
template <typename T, typename Base> int get_id(const Compound<T, Base> &c)
^
note: template argument deduction/substitution failed:
note: 'const Compound<T, Base>' is an ambiguous base class of 'B'
return get_id(var);
I understand why that is. B is derived and is convertible to both Compound<B, A> and Compound<A, Empty>
I'm wondering if it is possible to change (within context of C++14) Compound template and get_id() function such that it would return 0xa for A and 0xb for B and would work for arbitrarily long chains of inheritance.
I know that this can be easily solved with virtual function that is overridden in A and B, but I would like to avoid that if possible. Everywhere these types are used they are known and fixed at compile time so there shouldn't be a need to incur run-time overhead.
Just keep it simple:
template <class T>
auto get_id(T const& c) -> decltype(c.get_id())
{
return c.get_id();
}
You don't need c to be some Compound, you really just want it to have a get_id() member function.
It's not clear from your post why need to go the route of Compound in get_id. You can simply use:
template <typename T> int get_id(T const& c)
{
return T::id;
}

template instantiation with multiple template inheritance

What are the rules for template instantiation when we pass a (multi)derived class to a template function expecting base class? For example:
#include <iostream>
template <int x>
struct C {};
struct D : C<0>, C<1> {};
template <int x>
void f (const C<x> &y) { std::cout << x << "\n"; }
int main ()
{
f (D ());
}
MSVC 2015 prints 0, clang 3.8 - 1 and gcc 6.2 gives compiler error (Demo). And even if you SFINAE-away all overloads except one, the result will still be different:
#include <iostream>
template <int x> struct C {};
template<>
struct C<0> { using type = void; };
struct D : C<0>, C<1> {};
template <int x, typename = typename C<x>::type>
void f (const C<x> &y) { std::cout << x << "\n"; }
int main ()
{
f (D ());
}
Now it compiles only with MSVC, and if you swap C<0> and C<1> only clang will compile it. The problem is that MSVC only tries to instantiate first base, clang - last and gcc prints error too early. Which compiler is right?
gcc 5.4:
/tmp/gcc-explorer-compiler11685-58-1h67lnf/example.cpp: In function 'int main()':
13 : error: no matching function for call to 'f(D)'
f (D ());
^
9 : note: candidate: template<int x> void f(const C<x>&)
void f (const C<x> &y) { std::cout << x << "\n"; }
^
9 : note: template argument deduction/substitution failed:
13 : note: 'const C<x>' is an ambiguous base class of 'D'
f (D ());
^
Compilation failed
Which seems to me to be the correct result, since C<0> and C<1> are equally specialised.
Same result for gcc 6.2
clang 3.8.1 compiles it, which in my view is a compiler bug.
update:
I don't know the actual use case but I was wonder whether this might work for you:
#include <utility>
#include <iostream>
template<class T>
struct has_type
{
template<class U> static auto test(U*) -> decltype(typename U::type{}, std::true_type());
static auto test(...) -> decltype(std::false_type());
using type = decltype(test((T*)0));
static const auto value = type::value;
};
template <int x> struct C {};
template<>
struct C<0> { using type = int; };
template<int...xs>
struct enumerates_C : C<xs>...
{
};
struct D : enumerates_C<0, 1> {};
template<int x, std::enable_if_t<has_type<C<x>>::value>* = nullptr>
void f_impl(const C<x>& y)
{
std::cout << x << "\n";
}
template<int x, std::enable_if_t<not has_type<C<x>>::value>* = nullptr>
void f_impl(const C<x>& y)
{
// do nothing
}
template <int...xs>
void f (const enumerates_C<xs...> &y)
{
using expand = int[];
void(expand { 0,
(f_impl(static_cast<C<xs> const &>(y)),0)...
});
}
int main ()
{
f (D ());
}
expected output (tested on apple clang):
0

passing a method pointer as a template parameter: why can't I use an inherited method here?

The following code (condensed from a larger program) does not compile with clang or gcc.
struct S1 {
void m1() {}
};
template<typename B> struct S2 : B {
void m2() {}
void m3();
};
template<typename S, void (S::*m)()> void f1(S* o) {
(o->*m)();
}
template<typename B> void S2<B>::m3() {
f1<S2, &S2::m1>(this);
}
int main() {
void (S2<S1>::*m)() = &S2<S1>::m1;
S2<S1> o;
o.m3();
}
Here is clang's error message:
bad.cc:15:3: error: no matching function for call to 'f1'
f1<S2, &S2::m1>(this);
^~~~~~~~~~~~~~~
bad.cc:21:5: note: in instantiation of member function 'S2<S1>::m3' requested
here
o.m3();
^
bad.cc:10:43: note: candidate template ignored: invalid explicitly-specified
argument for template parameter 'm'
template<typename S, void (S::*m)()> void f1(S* o) {
^
1 error generated.
This code compiles when I replace m1 by m2. Clearly the compiler knows about m1 (different message when I replace m1 by m4), so why should a pointer to it be invalid in this context?
The thing is, the type of m1 is void(S1::*)(void), not void(S2::*)(void). So fix it by leveraging the known base class name:
struct S1 {
void m1() {}
};
template<typename B> struct S2 : B {
void m2() {}
void m3();
};
template<typename S, typename B, void (B::*m)(void)> void f1(S* o) {
(o->*m)();
}
template<typename B> void S2<B>::m3() {
f1<S2, B, &B::m1>(this);
}
int main() {
S2<S1> o;
o.m3();
}
Of course this doesn't (yet) scale to methods defined in indirect base classes, but with a bit of TMP it can be done (will see if I can post that while the intermission of Going Native 2012 lasts :))
The more 'flexible' approach would be:
template<typename B, typename MF> void f1(B* o, MF mfp) {
(o->*mfp)();
}
template<typename B> void S2<B>::m3() {
f1(this, &B::m1);
}
You could/should use typetraits to ensure that S2<B>& is convertible to a B& if the class layout doesn't already explicitly guarantee that, as in your current example.