首页 > 解决方案 > 我的 type_trait 在模板化/非模板化代码中的不同行为

问题描述

在以下代码段中,has_barmain 和DoStuff方法中的行为不同:

在 main 方法中,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;
}

标签: c++c++17typetraits

解决方案


它应该是:

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

演示


推荐阅读