在模板成员函数内部调用非模板成员函数

Calling non template member function inside template member function

本文关键字:函数 成员 调用 内部      更新时间:2023-10-16

我在运行以下程序时遇到编译问题:我在模板成员函数内部调用非模板成员函数,但却出现了奇怪的编译错误。

#include <iostream>
#include <boostshared_ptr.hpp>
class base
{
public:
    base()
    {
    }   
    void fun2(boost::shared_ptr<int> &data)
    {
        std::cout << "This is fun2" << std::endl;   
    }
    void fun3(boost::shared_ptr<double> &value)
    {
        std::cout << "This is fun3" << std::endl;
    }
    template <typename T>
    void fun1(int switchParam,T &resonse)
    {
        std::cout << "This is fun1." << std::endl;
        switch(switchParam)
        {
        case 0:
            fun2(resonse);
            break;
        case 1:
            fun3(resonse);
            break;
        }       
    }
};
void main()
{
    boost::shared_ptr<int> myInt;
    int switchParam = 0;
    base b1;
    b1.fun1(switchParam,myInt);
}

遇到以下编译问题:

Error   1   error C2664: 'base::fun3' : cannot convert parameter 1 from 'boost::shared_ptr<T>' to 'boost::shared_ptr<T> &'  

如有任何帮助,我们将不胜感激

否。你不能那样做。对于任何类型的模板代码编译的第二阶段,switch块必须由编译器完全编译。它将无法编译。您将templates和程序的运行时行为混合在一起。你最好写一个不同的函数。

请注意,switch是运行时,而不是编译时。当您将其称为fun1(0)时,编译器仍然必须为int完全编译它。它不会评估运行时的switch语句,也不会消除需要shared_ptr<double>fun3