读马修的回答后在这里,我决定试试这个自己.
我的尝试无法编译,因为SFINAE没有启动并剔除has_foo
尝试访问的功能T::foo
.
error: ‘struct Bar’ has no member named ‘foo’
Run Code Online (Sandbox Code Playgroud)
我错过了什么,或者是我试图以这种方式做不到的事情?
(我正在使用gcc-4.7.2)
完整示例如下:
#include <iostream>
// culled by SFINAE if foo does not exist
template<typename T>
constexpr auto has_foo(T& t) -> decltype((void)t.foo, bool())
{
return true;
}
// catch-all fallback for items with no foo
constexpr bool has_foo(...)
{
return false;
}
//-----------------------------------------------------
template<typename T, bool>
struct GetFoo
{
static int value(T& t)
{
return t.foo;
}
};
template<typename T>
struct GetFoo<T, false>
{
static int value(T&)
{
return 0;
}
};
//-----------------------------------------------------
template<typename T>
int get_foo(T& t)
{
return GetFoo<T, has_foo(t)>::value(t);
}
//-----------------------------------------------------
struct Bar
{
int val;
};
int main()
{
Bar b { 5 };
std::cout << get_foo(b) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Pup*_*ppy 11
AFAICS的主要问题是您使用运行时引用作为constexpr
函数参数.替换它可以正常工作.
#include <iostream>
// culled by SFINAE if foo does not exist
template<typename T>
constexpr auto has_foo(int) -> decltype(std::declval<T>().foo, bool())
{
return true;
}
// catch-all fallback for items with no foo
template<typename T> constexpr bool has_foo(...)
{
return false;
}
//-----------------------------------------------------
template<typename T, bool>
struct GetFoo
{
static int value(T& t)
{
return t.foo;
}
};
template<typename T>
struct GetFoo<T, false>
{
static int value(T&)
{
return 0;
}
};
//-----------------------------------------------------
template<typename T>
int get_foo(T& t)
{
return GetFoo<T, has_foo<T>(0)>::value(t);
}
//-----------------------------------------------------
struct Bar
{
int val;
};
struct Foo {
int foo;
};
int main()
{
Bar b { 5 };
Foo f { 5 };
std::cout << get_foo(b) << std::endl;
std::cout << get_foo(f) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)