In the following snippet, the has_bar
behaves differently in the main and the DoStuff
method:
In the main method, a_bar == false
and b_bar == true
.
When I execute this, I get 2x "Foo" as output. Why?
#include <iostream>
struct A
{
void Foo() { std::cout << "Foo" << std::endl; }
};
struct B : public A
{
void Bar() { std::cout << "Bar" << std::endl; }
};
template<typename, typename = void>
struct has_bar : std::false_type
{ };
template<typename T>
struct has_bar<T, std::void_t<decltype(T::Bar)>> : std::true_type
{ };
template<typename T>
void DoStuff(T t)
{
if constexpr (has_bar<T>::value)
{
t.Bar();
}
else
{
t.Foo();
}
}
int main()
{
A a;
B b;
constexpr bool a_bar = has_bar<A>::value; // false
constexpr bool b_bar = has_bar<B>::value; // true
DoStuff(a);
DoStuff(b);
std::cin.ignore();
return 0;
}
It should be:
template<typename T>
struct has_bar<T, std::void_t<decltype(&T::Bar)>> : std::true_type
// ^^
{ };
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With