使用CRTP导入函数重载

时间:2017-06-30 13:20:08

标签: c++ overloading crtp

我正在尝试以下方法:

template <typename T>
struct Wrapper
{
    T t;
};

template <class Derived>
struct wrapper_support
{
    template <typename T>
    bool operator ()(Wrapper<T> const & w) const
    {
        return static_cast<Derived const &>(*this)(w.t);
    }
};

struct functor : wrapper_support<functor>
{
    template <typename T>
    bool operator ()(T t) const {return t == 42;}
};

void test()
{
    functor f;
    std::cout << f(Wrapper<int>{42}) << std::endl;
}

但无法编译:在解析对f.operator ()的调用时,只会考虑functor::operator ()(T) const,因为它隐藏了wrapper_support&#39; s operator ()

将代码更改为

struct functor : wrapper_support<functor>
{
    using wrapper_support<functor>::operator ();
    template <typename T>
    bool operator ()(T t) const {return t == 42;}
};

解决了这个问题,但我希望我可以避免添加using指令。

编辑:

我最终使用宏实现了它:

#define WRAPPER_SUPPORT                           \
    template <typename T>                         \
    bool operator ()(Wrapper<T> const & w) const  \
    {                                             \
        return (*this)(w.t);                      \
    }

struct functor
{
    template <typename T>
    bool operator ()(T t) const {return t == 42;}

    WRAPPER_SUPPORT
};

但后来我遇到了一个新问题。为了更通用,我将宏更改为以下内容:

#define WRAPPER_SUPPORT                           \
    template <typename T>                         \
    auto operator ()(Wrapper<T> const & w) const  \
        -> decltype((*this)(w.t))                 \
    {                                             \
        return (*this)(w.t);                      \
    }

它再次陷入与Visual C ++ 2013相同的问题。

我尝试了Ideone上的代码(在C ++中,而不是在C ++ 14中),它运行良好。

这是Visual C ++的限制,是否有解决方法?

0 个答案:

没有答案
相关问题