std :: enable_if有条件地编译成员函数

时间:2011-08-07 11:02:54

标签: c++ templates g++ c++11

我正在尝试一个简单的示例来了解如何使用std::enable_if。在我阅读this answer之后,我认为想出一个简单的例子应该不会太难。我想使用std::enable_if在两个成员函数之间进行选择,并且只允许使用其中一个。

不幸的是,以下内容无法使用gcc 4.7进行编译,经过数小时和数小时的尝试后,我会问你们我的错误是什么。

#include <utility>
#include <iostream>

template< class T >
class Y {

    public:
        template < typename = typename std::enable_if< true >::type >
        T foo() {
            return 10;
        }
        template < typename = typename std::enable_if< false >::type >
        T foo() {
            return 10;
        }

};


int main() {
    Y< double > y;

    std::cout << y.foo() << std::endl;
}

gcc报告了以下问题:

% LANG=C make CXXFLAGS="-std=c++0x" enable_if
g++ -std=c++0x    enable_if.cpp   -o enable_if
enable_if.cpp:12:65: error: `type' in `struct std::enable_if<false>' does not name a type
enable_if.cpp:13:15: error: `template<class T> template<class> T Y::foo()' cannot be overloaded
enable_if.cpp:9:15: error: with `template<class T> template<class> T Y::foo()'

为什么g ++没有为第二个成员函数删除错误的实例化?根据标准,std::enable_if< bool, T = void >::type仅在布尔模板参数为true时存在。但是为什么g ++不认为这是SFINAE?我认为重载错误消息来自g ++不删除第二个成员函数的问题,并认为这应该是一个重载。

7 个答案:

答案 0 :(得分:100)

SFINAE仅在模板参数的参数推断中的替换使得构造不正确时才有效。没有这样的替代品。

  

我也想到了这一点,并试图使用std::is_same< T, int >::value! std::is_same< T, int >::value来获得相同的结果。

这是因为当实例化类模板时(在您创建类型为Y<int>的对象时会发生这种情况),它会实例化其所有成员声明(不一定是它们的定义/主体!)。其中还包括其成员模板。请注意,T已知,!std::is_same< T, int >::value会产生错误。因此,它将创建一个包含

的类Y<int>
class Y<int> {
    public:
        /* instantiated from
        template < typename = typename std::enable_if< 
          std::is_same< T, int >::value >::type >
        T foo() {
            return 10;
        }
        */

        template < typename = typename std::enable_if< true >::type >
        int foo();

        /* instantiated from

        template < typename = typename std::enable_if< 
          ! std::is_same< T, int >::value >::type >
        T foo() {
            return 10;
        }
        */

        template < typename = typename std::enable_if< false >::type >
        int foo();
};

std::enable_if<false>::type访问不存在的类型,因此声明格式不正确。因此您的程序无效。

您需要使成员模板“enable_if取决于成员模板本身的参数。然后声明是有效的,因为整个类型仍然是依赖的。当您尝试调用其中一个时,会发生模板参数的参数推断,并且SFINAE会按预期发生。请参阅this question以及有关如何执行此操作的相应答案。

答案 1 :(得分:69)

我做了这个简短的例子也可以。

#include <iostream>
#include <type_traits>

class foo;
class bar;

template<class T>
struct is_bar
{
    template<class Q = T>
    typename std::enable_if<std::is_same<Q, bar>::value, bool>::type check()
    {
        return true;
    }

    template<class Q = T>
    typename std::enable_if<!std::is_same<Q, bar>::value, bool>::type check()
    {
        return false;
    }
};

int main()
{
    is_bar<foo> foo_is_bar;
    is_bar<bar> bar_is_bar;
    if (!foo_is_bar.check() && bar_is_bar.check())
        std::cout << "It works!" << std::endl;

    return 0;
}

评论如果你想让我详细说明。我认为代码或多或少是不言自明的,但我再次做到这一点,所以我可能错了:)

您可以在行动here中看到它。

答案 2 :(得分:12)

对于那些正在寻找解决方案的后来者来说,只是工作&#34;:

#include <utility>
#include <iostream>

template< typename T >
class Y {

    template< bool cond, typename U >
    using resolvedType  = typename std::enable_if< cond, U >::type; 

    public:
        template< typename U = T > 
        resolvedType< true, U > foo() {
            return 11;
        }
        template< typename U = T >
        resolvedType< false, U > foo() {
            return 12;
        }

};


int main() {
    Y< double > y;

    std::cout << y.foo() << std::endl;
}

编译:

g++ -std=gnu++14 test.cpp 

跑步给出:

./a.out 
11

答案 3 :(得分:7)

来自this帖子:

  

默认模板参数不是模板签名的一部分

但是人们可以这样做:

#include <iostream>

struct Foo {
    template < class T,
               class std::enable_if < !std::is_integral<T>::value, int >::type = 0 >
    void f(const T& value)
    {
        std::cout << "Not int" << std::endl;
    }

    template<class T,
             class std::enable_if<std::is_integral<T>::value, int>::type = 0>
    void f(const T& value)
    {
        std::cout << "Int" << std::endl;
    }
};

int main()
{
    Foo foo;
    foo.f(1);
    foo.f(1.1);

    // Output:
    // Int
    // Not int
}

答案 4 :(得分:5)

解决这个问题的一种方法是,成员函数的特化是将特化放入另一个类,然后从该类继承。您可能必须更改继承的顺序才能访问所有其他基础数据,但这种方法确实有效。

template< class T, bool condition> struct FooImpl;
template<class T> struct FooImpl<T, true> {
T foo() { return 10; }
};

template<class T> struct FoolImpl<T,false> {
T foo() { return 5; }
};

template< class T >
class Y : public FooImpl<T, boost::is_integer<T> > // whatever your test is goes here.
{
public:
    typedef FooImpl<T, boost::is_integer<T> > inherited;

    // you will need to use "inherited::" if you want to name any of the 
    // members of those inherited classes.
};

这种技术的缺点是,如果你需要为不同的成员函数测试很多不同的东西,你必须为每个成员函数创建一个类,并将它链接到继承树中。这适用于访问公共数据成员。

例如:

template<class T, bool condition> class Goo;
// repeat pattern above.

template<class T, bool condition>
class Foo<T, true> : public Goo<T, boost::test<T> > {
public:
    typedef Goo<T, boost::test<T> > inherited:
    // etc. etc.
};

答案 5 :(得分:4)

布尔值需要依赖于推导出的模板参数。因此,一种简单的修复方法是使用默认的布尔参数:

template< class T >
class Y {

    public:
        template < bool EnableBool = true, typename = typename std::enable_if<( std::is_same<T, double>::value && EnableBool )>::type >
        T foo() {
            return 10;
        }

};

但是,如果要重载成员函数,这将无法工作。相反,最好使用TICK_MEMBER_REQUIRES库中的Tick

template< class T >
class Y {

    public:
        TICK_MEMBER_REQUIRES(std::is_same<T, double>::value)
        T foo() {
            return 10;
        }

        TICK_MEMBER_REQUIRES(!std::is_same<T, double>::value)
        T foo() {
            return 10;
        }

};

你也可以像这样实现你自己的成员需要宏(以防万一你不想使用另一个库):

template<long N>
struct requires_enum
{
    enum class type
    {
        none,
        all       
    };
};


#define MEMBER_REQUIRES(...) \
typename requires_enum<__LINE__>::type PrivateRequiresEnum ## __LINE__ = requires_enum<__LINE__>::type::none, \
class=typename std::enable_if<((PrivateRequiresEnum ## __LINE__ == requires_enum<__LINE__>::type::none) && (__VA_ARGS__))>::type

答案 6 :(得分:0)

这是我使用宏的简约示例。 使用更复杂的表达式时,请使用双括号enable_if((...))

template<bool b, std::enable_if_t<b, int> = 0>
using helper_enable_if = int;

#define enable_if(value) typename = helper_enable_if<value>

struct Test
{
     template<enable_if(false)>
     void run();
}
相关问题