【问题标题】:SFINAE to Selectively Include MemberSFINAE 选择性地包括成员
【发布时间】:2013-07-29 15:54:08
【问题描述】:

我正在尝试编写一个模板类,它可能会或可能不会定义特定的成员函数,具体取决于其模板参数类型。此外,此成员函数的返回类型取决于模板参数成员(如果已定义)的返回类型。

以下是我的代码的最小示例

#include <iostream>
#include <type_traits>

template <typename T>
struct has_foo_int {
private:
    template <typename U>
    static decltype(std::declval<U>().foo(0), void(), std::true_type()) test(int);
    template <typename>
    static std::false_type test(...);
public:
    typedef decltype(test<T>(0)) test_type;
    enum { value = test_type::value };
};

template <typename T, bool HasFooInt>
struct foo_int_return_type;

template<typename T>
struct foo_int_return_type<T,false> {};

template<typename T>
struct foo_int_return_type<T,true> {
    using type = decltype(std::declval<T>().foo(0));
};

template<typename T>
struct mystruct
{
    T val;

    //auto someMethod(int i) -> decltype(std::declval<T>().foo(0)) // error: request for member ‘foo’ in ‘std::declval<double>()’, which is of non-class type ‘double’
    //auto someMethod(int i) -> typename foo_int_return_type<T,has_foo_int<T>::value>::type // error: no type named ‘type’ in ‘struct foo_int_return_type<double, false>’
    template<typename R=typename foo_int_return_type<T,has_foo_int<T>::value>::type> R someMethod(int i) // error: no type named ‘type’ in ‘struct foo_int_return_type<double, false>’
    {
        return val.foo(i);
    }
};

struct with_foo_int {
    int foo(int i){
        return i+1;
    }
};

using namespace std;

int main(void)
{
    mystruct<with_foo_int> ms1;
    cout << ms1.someMethod(41) << endl;

    mystruct<double> ms2;

    return 0;
}

我希望代码编译良好并为ms1.someFunc(41) 输出 42。我还希望,如果有人不小心尝试在 ms2 上调用 someFunc,它将无法编译。

不幸的是,我尝试过的每个替代方案都失败了。第一个和第二个,我想我明白为什么它们不起作用了。

我读到here 说 SFINAE 仅适用于模板函数,因此我尝试提供一个虚拟模板参数来计算返回类型,但这也以同样的方式失败。

我显然不明白这里的某些东西,我错过了什么?是否有可能实现我想要做的事情?

谢谢。

附注我正在使用 g++ 4.7.3

P.p.s 我也尝试过 std::enable_if,但得到的结果与我的 foo_int_return_type 结构大致相同。

【问题讨论】:

  • 函数本身需要将相关参数作为模板参数,否则在调用点没有替换,你不会得到SFINAE。一种流行的解决方法是使用虚拟参数,例如 template&lt;class U = T, *insert SFINAE here with U instead of T*&gt;
  • 有效!不过,我不确定为什么,如果您将此作为答案发布并解释,我会很乐意接受。
  • 对于 SFINAE,编译器(或用户)需要推断(提供)一个类型,编译器稍后会尝试 S 替换和 F 一切
  • @Dan:不,触发 SFINAE 的表达式需要依赖 该函数的模板参数
  • @Dan: R 是一个单一的类型,它要么是提供的,要么是推导的,但是在解决了那个类型之后就没有替代

标签: c++ templates c++11 sfinae decltype


【解决方案1】:

这是一种简短、整洁且记录在案的方式来做您正在尝试的事情, 之后解决了一些可能的错误。

#include <type_traits>

/*
    Template `has_mf_foo_accepts_int_returns_int<T>`
    has a static boolean public member `value` that == true
    if and only if `T` is a class type that has a public
    member function or member function overload 
    `int T::foo(ArgType) [const]`  where `ArgType`
    is a type to which `int` is implicitly convertible.
*/
template <typename T>
struct has_mf_foo_accepts_int_returns_int {

    /* SFINAE success:
        We know now here `int *` is convertible to
        "pointer to return-type of T::foo(0)" 
    */
    template<typename A>
    static constexpr bool test(
        decltype(std::declval<A>().foo(0)) *prt) {
        /* Yes, but is the return-type of `T::foo(0)`
            actually *the same* as `int`?...
        */
        return std::is_same<int *,decltype(prt)>::value;
    }

    // SFINAE failure :(
    template <typename A>
    static constexpr bool test(...) {
        return false; 
    }

    /* SFINAE probe.
        Can we convert `(int *)nullptr to 
        "pointer to the return type of T::foo(0)"?
    */
    static const bool value = test<T>(static_cast<int *>(nullptr)); 
};

template<typename T>
struct mystruct
{
    using has_good_foo = has_mf_foo_accepts_int_returns_int<T>;

    T val;

    /*  SFINAE:
        `template<typename R> R someMethod(R)` will be this if and only
        if `R` == `int` and `has_good_foo` == true.         
    */
    template<typename R = int>
    typename std::enable_if<
        (has_good_foo::value && std::is_same<R,int>::value),R
    >::type 
    someMethod(R i) {
        return val.foo(i);
    }

    /*  SFINAE:
        `template<typename R> R someMethod(R)` will be this if and only
        if `R` != `int` or `has_good_foo` != true.      
    */
    template<typename R = int>
    typename std::enable_if<
        !(has_good_foo::value && std::is_same<R,int>::value),R
    >::type
    someMethod(R i) {
        static_assert(has_good_foo::value && std::is_same<R,int>::value,
            "mystruct<T> does not implement someMethod(R)");
        return i;
    }
};

// Testing...

#include <iostream>

struct with_foo_int
{
    int foo(int i) {
        return i + 1;
    }
};

using namespace std;

int main(void)
{
    mystruct<with_foo_int> ms1;
    cout << ms1.someMethod(41) << endl;

    mystruct<double> ms2;
    cout << ms2.someMethod(41) << endl; // static_assert failure

    return 0;
}

此解决方案忠实地再现了您的几个可能的漏洞 发布的自己的尝试:-

1) 看起来您可能认为评估 std::declval&lt;U&gt;().foo(0) 是 确定U::foo 是否存在并采用单个参数的 SFINAE 方法 int 类型。它没有。这只是 SFINAE 确定是否 U::foo(ArgType) 存在于其中 ArgType0 的任何东西 隐式可转换。因此ArgType 可以是任何指针或算术 输入,而不仅仅是int

2)你可能没有想到std::declval&lt;U&gt;().foo(0)会满足 如果U::foo(ArgType) U::foo(ArgType) const 中的任何一个或两者都存在。你 可能很关心您是否调用const 或非const 成员函数 U,你肯定会关心你调用了两个成员函数中的哪一个。如果 with_foo_int 被定义为:

struct with_foo_int
{
    int foo(int i) const {
        return i + 1;
    }
    int foo(int i) {
        return i + 2;
    }   
};

那么给出的解决方案将调用非const 重载和 ms1.someMethod(41) 会 == 43

2) 容易处理。如果你想确保你只能打电话 T::foo(ArgType) const 然后将const 限定符添加到mystruct::someMethod。 如果您不关心或只想打电话给T::foo(ArgType),那就留下吧 就像他们一样。

1) 有点难解决,因为你必须制作一个 SNIFAE 探针 T::foo 只有当它具有正确的签名时才满足,并且 签名将是const 合格或不合格。假设你想要 int T::foo(int) const。在这种情况下,替换模板 has_mf_foo_accepts_int_returns_int 与:

/*  Template `has_mf_foo_arg_int_returns_int<T>
    has a static boolean public member `value` that == true
    if and only if `T` is a class type that has an un-overloaded
    a public member `int T::foo(int) const`.
*/ 
template< typename T>
struct has_mf_foo_arg_int_returns_int
{
    /* SFINAE foo-has-correct-sig :) */
    template<typename A>
    static std::true_type test(int (A::*)(int) const) {
        return std::true_type();
    }

    /* SFINAE foo-exists :) */
    template <typename A> 
    static decltype(test(&A::foo)) 
    test(decltype(&A::foo),void *) {
        /* foo exists. What about sig? */
        typedef decltype(test(&A::foo)) return_type; 
        return return_type();
    }

    /* SFINAE game over :( */
    template<typename A>
    static std::false_type test(...) {
        return std::false_type(); 
    }

    /* This will be either `std::true_type` or `std::false_type` */
    typedef decltype(test<T>(0,0)) type;

    static const bool value = type::value; /* Which is it? */
};

并在模板mystruct 中替换:

using has_good_foo = has_mf_foo_accepts_int_returns_int<T>;

与:

using has_good_foo = has_mf_foo_arg_int_returns_int<T>;

(模板has_mf_foo_arg_int_returns_int已适配 来自my other answer 和 你可以在那里阅读它是如何工作的。)

您从后一种方法中获得的 SFINAE 精度来自于 一个价格。该方法要求您尝试获取T::foo的地址, 看看它是否存在。但是 C++ 不会给你重载的地址 成员函数,因此如果 T::foo 重载,此方法将失败。

这里的代码将编译(或适当的static_assert) GCC >= 4.7.2 铿锵声 >= 3.2。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    相关资源
    最近更新 更多