【发布时间】:2015-07-20 20:09:15
【问题描述】:
我正在尝试编译这个示例,其中可变参数类模板继承自可变数量的基,每个基都实现不同的operator[]:
#include <iostream>
template <typename T>
struct Field {
typename T::value_type storage;
typename T::value_type &operator[](const T &c) {
return storage;
}
};
template<typename... Fields>
struct ctmap : public Field<Fields>... {
};
int main() {
struct age { typedef int value_type; };
struct last_name { typedef std::string value_type; };
ctmap<last_name, age> person;
person[last_name()] = "Smith";
person[age()] = 104;
std::cout << "Hello World!" << std::endl;
return 0;
}
当我使用 gcc (Debian 4.9.2-10) 编译时,出现以下错误
main.cpp: In function ‘int main()’:
main.cpp:22:23: error: request for member ‘operator[]’ is ambiguous
person[last_name()] = "Smith";
^
main.cpp:7:27: note: candidates are: typename T::value_type& Field<T>::operator[](const T&) [with T = main()::age; typename T::value_type = int]
typename T::value_type &operator[](const T &c) {
^
main.cpp:7:27: note: typename T::value_type& Field<T>::operator[](const T&) [with T = main()::last_name; typename T::value_type = std::basic_string<char>]
main.cpp:23:17: error: request for member ‘operator[]’ is ambiguous
person[age()] = 104;
^
main.cpp:7:27: note: candidates are: typename T::value_type& Field<T>::operator[](const T&) [with T = main()::age; typename T::value_type = int]
typename T::value_type &operator[](const T &c) {
^
main.cpp:7:27: note: typename T::value_type& Field<T>::operator[](const T&) [with T = main()::last_name; typename T::value_type = std::basic_string<char>]
为什么这是模棱两可的?
【问题讨论】:
-
这被clang++3.8接受:melpon.org/wandbox/permlink/huzwGp0kc2OafMZl(但我不确定在这种情况下哪个编译器是正确的)
-
(基本上多个基类中的成员函数不会重载。不过我不确定这如何与运算符查找交互;乍一看,clang 似乎是错误的。)
-
您可以使其符合基于线性/树的继承和
using声明。 -
是真正的dyp,我用clang 3.6在coliru中尝试这个代码并且工作正常,但我需要使用gcc,在这种情况下版本是4.9.2。
-
Yakk,你能解释一下如何进行线性/树基继承吗?你能举个例子吗?
标签: c++ c++11 operator-overloading variadic-templates ambiguous