【发布时间】:2016-09-28 14:16:56
【问题描述】:
我正在寻找一个 SFINAE 解决方案来在编译时检查一个类型是否有方法。我的目标是检查一个类型是否是有效的"duck type",但我想使用static_assert 来提供信息性消息,而不是无用的编译错误。
我找到了 [this question],它为我的问题提供了一个相当好的答案,但当类型为方法提供重载时它会失败:
template<typename...> // parameter pack here
using void_t = void;
template<typename T, typename = void>
struct has_xxx : std::false_type {};
template<typename T>
struct has_xxx<T, void_t<decltype(&T::xxx)>> :
std::is_member_function_pointer<decltype(&T::xxx)>{};
这适用于以下示例,并区分方法和成员变量:
struct Foo { int xxx() {return 0;}; };
struct Foo2 {};
struct Foo3{ static double xxx;};
double Foo3::xxx = 42;
int main() {
static_assert(has_xxx<Foo>::value, "");
static_assert(!has_xxx<Foo2>::value, "");
static_assert(!has_xxx<Foo3>::value, "");
}
如果出现重载,代码会失败:
struct Foo { int xxx() {return 0;} void xxx(int){} };
int main() {
static_assert(has_xxx<Foo>::value, "");
}
Failing live demo with overloaded method
如何改进此代码以处理重载?
【问题讨论】:
-
好吧,你想测试什么?只要名称
xxx完全存在(为什么?),或者如果您可以使用一些参数(哪些参数?)调用xxx? -
我不认为如果函数重载时不提供附加参数是否可行。但我很想看到一个答案:)
-
我认为这里的问题和答案可能比@iammilind 链接到的问题更全面。也许这应该被标记为骗子,而不是保留这个问题?
-
这个问题不是重复的,因为在这里 OP 增加了重载方法的可能性,而张贴的作者没有。
标签: c++ c++11 c++14 template-meta-programming