SFINAE decltype逗号操作员技巧

时间:2013-08-16 03:54:38

标签: c++ c++11 sfinae

在阅读了Matthieu的回答here之后,我决定自己尝试一下。

我的尝试无法编译,因为SFINAE没有启动并剔除试图访问has_foo的{​​{1}}函数。

T::foo

我错过了什么,或者是我试图以这种方式做不到的事情?

(我正在使用gcc-4.7.2)

下面的完整示例:

error: ‘struct Bar’ has no member named ‘foo’

1 个答案:

答案 0 :(得分: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;
}