簡體   English   中英

無法在VS .NET 2008中使用boost :: enable_if專門化成員函數模板

[英]Unable to specialize a member function template with boost::enable_if in VS .NET 2008

我試圖專門針對兩種不同類型的類的成員函數模板,如下所示:

#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)'

我建議使用標簽分發: 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; }

您不能部分專門化(成員)功能模板。 故事結局。

即使可以,您也應該擁有一個對SFINAE友好的主模板。 用偽代碼:

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

如果您已經准備好類模板(例如仿函數或僅定義非模板方法的類型...),則仍可以使用此技術。

根據經驗,對於功能模板 ,重載解析提供了靜態多態性,從而消除了部分專業化的需求。 看到

兩者均來自Herb Sutter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM