【问题标题】:Calling non template member function inside template member function在模板成员函数中调用非模板成员函数
【发布时间】:2016-05-19 04:32:35
【问题描述】:

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

#include <iostream>
#include <boost\shared_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> &'  

我们将不胜感激。

【问题讨论】:

  • fun3 需要一个指向 double 的指针,您正在尝试编译它并传递一个指向 int 的指针,显然编译器不喜欢它。这有什么奇怪的?
  • 我想在 fun1 中传递不同的数据类型,但根据情况,它应该相应地调用不同的函数。
  • 如果我不传递 shared_ptr 并使用默认数据类型,如 int 或 double,则同样的工作。
  • 你在编译时就知道类型,为什么不重载一个函数?
  • 这与模板无关。您在未采用的代码分支中出现类型错误,并希望摆脱它。 if(false) { int a = "foo"; }。不行,行不通。重新设计你的逻辑。

标签: c++ templates boost shared-ptr


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多