代码之家  ›  专栏  ›  技术社区  ›  Joris Timmermans

VS2010 C++成员模板函数特化误差

  •  2
  • Joris Timmermans  · 技术社区  · 14 年前

    我有以下(最小化的)代码,在VC2005中有效,但在2010年不再有效。

    template <typename TDataType>
    class TSpecWrapper
      { 
      public:
        typedef typename TDataType::parent_type index_type;
    
    
      public:
    
        template <bool THasTriangles>
        void Spec(index_type& io_index)
          { std::cout << "False version" << std::endl; }
    
        template <>
        void Spec<true>(index_type& io_index)
          { std::cout << "True version" << std::endl; }
      };
    

    似乎当“index\u type”是依赖类型时,我总是在专门化上得到一个C2770:invalid explicit template参数错误。请注意,这段代码实际上足以生成错误-一个空的main就足以编译它,甚至不需要实例化模板。

    如果索引类型不是依赖类型,则可以正常工作。你知道为什么在VC2010中会这样吗,这是不是标准的行为或者一个bug,我是否可以解决它?

    2 回复  |  直到 14 年前
        1
  •  7
  •   Alexey Malistov    14 年前

    变通办法

    template <bool v> struct Bool2Type { static const bool value = v; }; 
    
    template <typename TDataType> 
    class TSpecWrapper 
    {  
    public: 
        typedef typename TDataType::parent_type index_type; 
    
    
    public: 
        template <bool THasTriangles> 
        void Spec(index_type& io_index) 
        { 
            return SpecHelp(io_index, Bool2Type<THasTriangles>());
        } 
    
    private:
        void SpecHelp(index_type& io_index, Bool2Type<false>) 
        { std::cout << "False version" << std::endl; } 
    
        void SpecHelp(index_type& io_index, Bool2Type<true>) 
        { std::cout << "True version" << std::endl; } 
    
    }; 
    
        2
  •  4
  •   Kirill V. Lyadvinsky    14 年前

    这是根据C++标准的。

    在类模板或出现的成员模板的成员的显式专门化声明中 在名称空间范围内,成员模板和它的一些封闭类模板可能保持非专用性, 模板也没有显式专门化 . <&燃气轮机;

    不允许专攻 Spec 没有专业知识 TDataType .