c++ - 从2个模板类继承 `sameFunctionName<T>()` ==>不明确

标签 c++ templates c++17 template-argument-deduction

我有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/

相关文章:

c++ - 我可以使用类级别的 typedef 作为基类的模板参数吗?

c++ - header 中的内联和 constexpr 无捕获 lambda 有什么区别?

c++ - 基于std::any的属性系统:模板类型推导

javascript - 如何更改 Meteor 模板中的 CSS 属性?

c++ - 在 C++ 中通过 Pthread_Create 打印通过结构传递的数组值

c++ - 如何使用 std::copy 读取任意数量的值?

c++ - 具有重载赋值运算符的可变字段

c++ - 默认初始化模板中的指针

C++ 17 为什么不删除二合字母和三合字母?

c++ - OpenCV-cvQueryFrame()