boost:enable_if to define a dedicated method in a templated class

雨燕双飞 提交于 2019-12-13 07:40:34

问题


I would like to have a custom method - I will call MyMethod - in a templated class - I will call Foo - ONLY when Foo has been instanciated with certain template parameters types (eg. when A is int and B is string), otherwise, I don't want MyMethod to exist at all on any other possible Foo instance.

Is that possible ?

Example:

template<class A, class B>
class Foo
{
    string MyMethod(whatever...);
}

boost:enable_if can help there ?

Thanks!!


回答1:


What you really want here is to specialize your template. In your example, you would write:

template<>
class Foo<int, string>
{
    string MyMethod(whatever...); 
};

you can also use enable_if:

template<typename A, typename B>
class Foo
{
    typename boost::enable_if<
            boost::mpl::and_<
                boost::mpl::is_same<A, int>,
                boost::mpl::is_same<B, string>
            >,
            string>::type MyMethod(whatever...){}
};

if there are no overloads, you can also use static_assert:

template<typename A, typename B>
class Foo
{
    string MyMethod(whatever...)
    {
         static_assert(your condition here, "must validate condition");
         // method implementation follows
    }
};

this will produce a compile error when you try to invoke MyMethod and the condition is not set.



来源:https://stackoverflow.com/questions/11242445/boostenable-if-to-define-a-dedicated-method-in-a-templated-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!