我试图专门针对两种不同类型的类的成员函数模板,如下所示:

#include <iostream>
#include <boost/utility/enable_if.hpp>

struct Wibble
{
    static const bool CAN_WIBBLE = true;
};

struct Wobble
{
    static const bool CAN_WIBBLE = false;
};

struct Foo
{
    //template<typename T>   // Why isn't this declaration sufficient?
    //void doStuff();

    template<typename T>
    typename boost::enable_if_c<T::CAN_WIBBLE,void>::type
    doStuff();

    template<typename T>
    typename boost::enable_if_c<!T::CAN_WIBBLE,void>::type
    doStuff();
};

template<typename T>
typename boost::enable_if_c<T::CAN_WIBBLE,void>::type
Foo::doStuff()
{
    std::cout << "wibble ..." << std::endl;
}

template<typename T>
typename boost::enable_if_c<!T::CAN_WIBBLE,void>::type
Foo::doStuff()
{
    std::cout << "I can't wibble ..." << std::endl;
}

int main()
{
    Foo f;
    f.doStuff<Wibble>();
    f.doStuff<Wobble>();
}

GCC 4.8.2会编译代码,而VS .NET 2008会吐出错误消息:
error C2244: 'Foo::doStuff' : unable to match function definition to an existing declaration

        definition
        'boost::enable_if_c<!T::CAN_WIBBLE,void>::type Foo::doStuff(void)'
        existing declarations
        'boost::enable_if_c<!T::CAN_WIBBLE,void>::type Foo::doStuff(void)'
        'boost::enable_if_c<T::CAN_WIBBLE,void>::type Foo::doStuff(void)'

最佳答案

我建议使用标签分派(dispatch):https://ideone.com/PA5PTg

struct Foo
{
    template<bool wibble>
    void _doStuff();

public:
    template<typename T>
    void doStuff()
    {
        _doStuff<T::CAN_WIBBLE>();
    }
};

template<>
void Foo::_doStuff<true>() { std::cout << "wibble ..." << std::endl; }

template<>
void Foo::_doStuff<false>() { std::cout << "I can't wibble ..." << std::endl; }

关于c++ - 无法在VS .NET 2008中使用boost::enable_if专门化成员函数模板,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22789730/

10-12 16:57