Gia*_*tta 8 c++ templates operator-overloading
我在使用g ++编译我的库中与operator []相关的片段时遇到了问题.
我用这段代码重新创建了同样的问题:
template<class A,class B> class X {
public:
template<class C> X<C,B>& operator[]( const C& );
};
template<class A,class B,class C> class Y : public X<C,B> {
friend X<C,B>& X<A,B>::template operator[]<C>( const C& );
private:
Y( X<A,B>& object , const C& index ) : X<C,B>() {};
};
template<class A,class B> template<class C> X<C,B>& X<A,B>::operator[]( const C& index ) {
return *( new Y<A,B,C>( *this , index ) );
}
int main() {
X<int,void> x;
X<int,void>& y = x[2];
}
Run Code Online (Sandbox Code Playgroud)
g ++退出时出现以下错误:
./src/test.cpp: In instantiation of ‘Y<int, void, int>’:
./src/test.cpp:14: instantiated from ‘X<C, B>& X<A, B>::operator[](const C&) [with C = int, A = int, B = void]’
./src/test.cpp:19: instantiated from here
./src/test.cpp:8: error: ‘operator[]’ not defined
./src/test.cpp: In member function ‘X<C, B>& X<A, B>::operator[](const C&) [with C = int, A = int, B = void]’:
./src/test.cpp:19: instantiated from here
./src/test.cpp:10: error: ‘Y<A, B, C>::Y(X<A, B>&, const C&) [with A = int, B = void, C = int]’ is private
./src/test.cpp:14: error: within this context
Run Code Online (Sandbox Code Playgroud)
我认为问题出在Y类的'operator []'的朋友声明中,但我不知道它出错了.我试着搜索自己,但找不到任何有用的东西.谁能帮我?
谢谢,詹尼
由于你没有说出你真正的设计目标是什么,所以提出一些好的东西有点困难,但至少使用
template<class CC> friend X<CC,B>& X<A,B>::operator[]( const CC& );
Run Code Online (Sandbox Code Playgroud)
因为朋友声明将使它编译,因为这告诉它是一个模板。
编辑:
再想一想,我认为您的代码也应该可以工作,因为它没有指定专门化。您是否尝试过使用 clang 来测试它?这似乎是 gcc 中的一个错误......