“未定义模板的隐式实例化”。在向前声明模板类时 [英] "Implicit instantiation of undefined template" when forward declaring template class

查看:292
本文介绍了“未定义模板的隐式实例化”。在向前声明模板类时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码需要向前声明模板类(或者至少,向前声明会使我更轻松...)。我已经编写了该问题的简化版本,因此可以在此处显示:

I've got some code in which I need to forward-declare the a template class (or at least, forward-declaring would make things a lot easier for me...). I've written a simplified version of the problem I'm having so I can display it here:

template<bool>
class MyTemplateClass;

int main( int argc, char* argv[] )
{
    MyTemplateClass<false> myTemp;  // error here
    myTemp.GetTheValue();
    return 0;
}

template<bool bShouldMult>
class MyTemplateClass
{
    int m_myint;
    float m_myfloat;

public:
    MyTemplateClass() : m_myint(5), m_myfloat(3.0f) {}
    float GetTheValue()
    {
        return m_myint * (bShouldMult ? m_myfloat : 1.0f);
    }   

};

我在注释行中遇到的错误是:

The error I'm getting at the commented line is:

Error - implicit instantiation of undefined template 'MyTemplateClass<false>'


的隐式实例化

在MyTemplateClass的前向声明中还需要包括哪些其他细节?由于错误不是来自下一行,因此我认为不是由于该方法未定义而引起的。我正在使用的编译器是LLVM / CLang,并且我正在Mac上进行编译。

What other detail do I need to include in a forward declaration of MyTemplateClass? Since the error isn't coming from the next line down I'm assuming it isn't due to the fact that the method is undefined. The compiler I'm using is LLVM/CLang, and I'm compiling on Mac.

推荐答案

为了声明变量任何类型的模板(无论是否具有模板),该类型的整个定义都必须可用。您无法向前声明模板,然后像定义模板一样开始使用它。此时,您所能做的就是声明一个指向基于模板的类型的对象的指针,如下所示:

In order to declare a variable of any type, template or not, the entire definition of that type must be available. You cannot forward-declare a template, and then start using it as if it were defined. All you can do at that point is declaring a pointer to an object of a type based on the template, like this:

MyTemplateClass<false> *myTempPtr;  // No error here

不幸的是(但并非意外),这会将错误移至下一行。初始化该指针的问题仍然存在:一旦尝试调用 new MyTemplateClass< false> ,就会看到错误。

Unfortunately (but not unexpectedly) this moves the error to the next line. The problem of initializing that pointer remains: once you attempt to invoke new MyTemplateClass<false>, you will see an error.

您需要重新排列代码,以将模板的定义移至其使用位置之前。这可能有点乏味,但是却无法解决:在开始实例化模板并调用其方法时,编译器需要具有完整的定义。

You need to re-arrange your code to move the definition of the template ahead of its place of use. This may be somewhat tedious, but there is no way around it: the compiler needs to have the entire definition at the point where you start instantiating your template and calling its methods.

这篇关于“未定义模板的隐式实例化”。在向前声明模板类时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆