template <typename T>
struct has_foo
{
template <typename C> static constexpr std::true_type test(decltype(&C::foo)) { return {}; }
template <typename C> static constexpr std::false_type test(...) { return {}; }
static constexpr bool value = test<T>(nullptr);
};
template <typename T> inline constexpr bool has_foo_v = has_foo<T>::value;
首先是传统的测试成员函数foo是否存在的代码,然后有两个结构
struct X {};
struct S { void foo() {}; };
如果用if的话
template <typename T>
void bar(T t)
{
if (has_foo_v<T>)
{
t.foo();
std::puts("yes");
}
else
{
std::puts("no");
}
}
那么在调用bar(X{})时,会编译出错,因为t.foo()不存在。如果把if改成if constexpr的话,编译无问题,因为if constexpr会把不符合条件的分支代码直接在编译时去掉,所以不会发生编译错误
如果编译器不支持if constexpr的话,可以用传统的模版重载解决
template <typename T, typename=std::enable_if_t<has_foo_v<T>>>
void bar(T t)
{
t.foo();
std::puts("yes");
}
void bar(...) {
std::puts("no");
}
文章介绍了如何使用模板元编程在C++中检测类型T是否具有成员函数foo,通过has_foo结构体和ifconstexpr实现编译时检查。当编译器不支持ifconstexpr时,可以借助模板重载来避免编译错误。
1025

被折叠的 条评论
为什么被折叠?



