简体   繁体   中英

Is there a way to disable member function in a template class in c++ for visual studio 2010 ( no default function template params )

For example

#include "boost/type_traits.hpp"
template <bool enable>
struct Foo {

    template <bool e = enable>
    typename boost::enable_if_c<e,void>::type  DoStuff(){}

};

int main(){
    // Compiles
    Foo<true>().DoStuff();
    // Fails
    Foo<false>().DoStuff();
}

will work in modern compilers but not with visual studio 2010 which does not allow default template params for functions / methods. Is there another way to formulate the same task that will work with VS2010?

You could specialize the entire class like

template <bool enable>
struct Foo {};

template <>
struct Foo<true> {
    void DoStuff(){}
};

template <>
struct Foo<false> {

};

And then

int main(){
    // Compiles
    Foo<true>().DoStuff();
    // Fails
    Foo<false>().DoStuff();
}

You could discard DoStuff via SFINAE:

template<bool enable>
struct Foo {
private:
    static void SFINAE_Helper(std::true_type);
    typedef std::integral_constant<bool, enable> tag;
public:
    decltype(SFINAE_Helper(tag())) DoStuff() { }
};

Besides the fact that this code is quite unreadable it has the advantage, that you do not need to make extra specializations but can have all your code in one class template.

EDIT

An alternative could look like that:

template<bool enable>
struct Foo {
private:
    typedef std::enable_if<enable> enable_tag;
public:
    typename enable_tag::type DoStuff() {}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM