我的 type_trait 在 templated/non-templated 代码中的不同行为
Different behaviour of my type_trait in templated/non-templated code
在以下代码片段中,has_bar
在主方法和 DoStuff
方法中的行为不同:
在main方法中,a_bar == false
和b_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;
}
应该是:
template<typename T>
struct has_bar<T, std::void_t<decltype(&T::Bar)>> : std::true_type
// ^^
{ };
在以下代码片段中,has_bar
在主方法和 DoStuff
方法中的行为不同:
在main方法中,a_bar == false
和b_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;
}
应该是:
template<typename T>
struct has_bar<T, std::void_t<decltype(&T::Bar)>> : std::true_type
// ^^
{ };