【问题标题】:C++ template specialisation & inheritanceC++ 模板特化和继承
【发布时间】:2015-12-03 11:10:34
【问题描述】:

我有以下一段代码,它应该声明基本结构,然后声明从它继承的模板结构。然后结构被部分指定。

#include <utility>
#include <iostream>

template<class A, class B>
struct Parent {
    std::pair<A, B> m_pair;
    void print() {
        std::cout << m_pair.first << ", " << m_pair.second << "\n";
    }
};

template <class A, class B>
struct Some : public Parent<A, B> {
    Some(A a, B b) : Parent<A, B>({ {a, b} }) {}
    void add() {
        m_pair.first += m_pair.second;
    }
};

template <class B>
struct Some<B, float> : public Parent<B, float> {
    Some(B a, float b) : Parent<B, float>({ {a, b} }) {}
    void add() {
        m_pair.first -= m_pair.second;
    }
};

int main() {
    Some<int, float> s(4, 42);
    s.add(); 
    s.print();
    return 0;
}

当我在 Visual Studio 2015 中编译它时,一切都可以正常编译并按预期工作。但是,当我使用 GCC 5.2.1 或 clang 3.6 编译时,出现以下错误:

untitled.cpp: In member function ‘void Some<A, B>::add()’:
untitled.cpp:17:9: error: ‘m_pair’ was not declared in this scope  
         m_pair.first += m_pair.second;  
         ^
untitled.cpp: In member function ‘void Some<B, float>::add()’:
untitled.cpp:24:9: error: ‘m_pair’ was not declared in this scope
         m_pair.first += m_pair.second;

怎么了?但是,当我将 m_pair 称为 Parent&lt;A, B&gt;::m_pair 时,它适用于 GCC 和 clang。

定义共享通用方法的特定模板类(使用特定方法)的正确方法是什么?

【问题讨论】:

    标签: c++ visual-c++ gcc clang++


    【解决方案1】:

    由于基类依赖于模板参数,因此在非限定名称查找期间不会检查基类成员。

    幸运的是,修复很简单:只需在基本成员访问前加上 this-&gt;:

    this->m_pair.first += this->m_pair.second;
    this->m_pair.first -= this->m_pair.second;
    

    在基类中查找,因此会找到该成员。

    非限定查找在 MSVC 中有效,因为该编译器在其模板实现的许多方面都不一致。

    【讨论】:

      猜你喜欢
      • 2013-06-08
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多