【发布时间】: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<A, B>::m_pair 时,它适用于 GCC 和 clang。
定义共享通用方法的特定模板类(使用特定方法)的正确方法是什么?
【问题讨论】:
标签: c++ visual-c++ gcc clang++