Tho*_* B. 4 c++ type-traits c++17
在以下代码段中,has_bar
行为主体和DoStuff
方法的行为有所不同:
在主要方法中,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;
}
Run Code Online (Sandbox Code Playgroud)
它应该是:
template<typename T>
struct has_bar<T, std::void_t<decltype(&T::Bar)>> : std::true_type
// ^^
{ };
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
122 次 |
最近记录: |