我的type_trait在模板/非模板代码中的不同行为

Tho*_* B. 4 c++ type-traits c++17

在以下代码段中,has_bar行为主体和DoStuff方法的行为有所不同:

在主要方法中,a_bar == falseb_bar == true

执行此命令时,输出为2x“ Foo”。为什么?

#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;
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*d42 7

它应该是:

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

演示版