Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behaviour of my type_trait in templated/non-templated code

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;
}
like image 556
Thomas B. Avatar asked Mar 04 '23 21:03

Thomas B.


1 Answers

It should be:

template<typename T>
struct has_bar<T, std::void_t<decltype(&T::Bar)>> : std::true_type
//                                     ^^
{ };

Demo

like image 59
Jarod42 Avatar answered Apr 27 '23 00:04

Jarod42