我有C<T>
来管理特定的原始类型T
。
为了方便使用,我想将C<int>
和C<float>
的所有功能分组到Utility
中。
template<typename T> class B{};
template<typename T> class C{
public: static void foo(B<T> bt){}
/** complex implemention in .cpp (I use explicit instantiation) */
/** a lot of functions!!!!!, each one with a lot of parameters */
};
class Utility: public C<int>,public C<float>{};
int main(){
B<int> bInt;
Utility::foo(bInt); //I don't want to change this line
}
Coliru MCVE我希望
Utility::foo(bInt)
与C<int>::foo(bInt)
具有相同的含义,但是出现此错误:-main.cpp: In function 'int main()':
main.cpp:9:14: error: reference to 'foo' is ambiguous
9 | Utility::foo(bInt); //I don't want to change this line
| ^~~
main.cpp:3:25: note: candidates are: 'static void C<T>::foo(B<T>) [with T = float]'
3 | public: static void foo(B<T> bt){}
| ^~~
main.cpp:3:25: note: 'static void C<T>::foo(B<T>) [with T = int]'
我不想更改foo
的调用方式。我喜欢它的方式,除了它不编译。
看来编译器无法推断并调用正确的T函数。
如何解决编译错误?
请注意,我在
C
中有很多功能。cigien 的解决方案效果很好,除了它对于我的情况而言可能是乏味的。
类似的问题:Ambiguous multiple inheritance of template classes(对于我的情况非常繁琐)
最佳答案
您可以将所需的特定版本foo
引入C
中,如下所示:
class Utility : public C<int>, public C<float>
{
public:
using C<int>::foo;
using C<float>::foo;
};
现在,模板参数推导可以推断出要调用的正确foo
。这是demo。
关于c++ - 从2个模板类继承 `sameFunctionName<T>()` ==>不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64002663/