代码之家  ›  专栏  ›  技术社区  ›  Matthieu M.

enable\ if+disable\ if组合引发不明确呼叫

  •  5
  • Matthieu M.  · 技术社区  · 14 年前

    在试图回答的时候 this question enable_if + disable_if 允许基于类型是(或不是)多态性的事实来重载方法。

    template <class T>
    void* address_of(T* p,
                     boost::enable_if< boost::is_polymorphic<T> >* dummy = 0)
    { return dynamic_cast<void*>(p); }
    
    template <class T>
    void* address_of(T* p,
                     boost::disable_if< boost::is_polymorphic<T> >* dummy = 0)
    { return static_cast<void*>(p); }
    
    struct N { int x; };
    
    
    int main(int argc, char* argv[])
    {
      N n;
      std::cout << address_of(&n) << std::endl;
      return 0;
    }
    

    这似乎很温和。

    然而,gcc(3.4…)对此感到窒息:

    int main(int, char**)
    测试cpp:29:错误:调用重载 address_of(N*) 是模棱两可的
    void* address_of(T*, boost::enable_if<boost::is_polymorphic<T>, void>*)
    test.cpp:20:注: void* address_of(T*, boost::disable_if<boost::is_polymorphic<T>, void>*) [T=N时]

    我用电脑把它修好了 ... (省略号)代替 需要一个虚假的第二个论点。。。但我仍然对编译器为什么会在这个问题上窒息感兴趣。

    2 回复  |  直到 7 年前
        1
  •  11
  •   Anthony Williams    14 年前

    ::type enable_if disable_if . 模板总是被定义的;只是成员 type 当且仅当表达式 true (用于 启用\u if )或者 false (用于 ).

    template <class T>
    void* address_of(T* p,
                     typename boost::enable_if< boost::is_polymorphic<T> >::type* dummy = 0)
    { return dynamic_cast<void*>(p); }
    
    template <class T>
    void* address_of(T* p,
                     typename boost::disable_if< boost::is_polymorphic<T> >::type* dummy = 0)
    { return static_cast<void*>(p); }
    

    没有尾随 ●类型 ●类型 ,则模板会使用第二个类型为的参数创建重载 void* ,或过载被消除(即期望的行为)。

        2
  •  0
  •   ngoozeff    14 年前

    在3.4.4中使用“返回类型”版本的enable\ u if: gcc version 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)

    #include <boost/utility/enable_if.hpp>
    #include <boost/type_traits/is_polymorphic.hpp>
    #include <iostream>
    
    template <class T>
    typename boost::enable_if< boost::is_polymorphic<T>, void* >::type
    address_of(T* p)
    { return dynamic_cast<void*>(p); }
    
    template <class T>
    typename boost::disable_if< boost::is_polymorphic<T>, void* >::type
    address_of(T* p)
    { return static_cast<void*>(p); }
    
    struct N { int x; };
    
    
    int main(int argc, char* argv[])
    {
      N n;
      std::cout << address_of(&n) << std::endl;
      return 0;
    }