【问题标题】:C++ - Template Class -> Static function -> Link error for static function pointerC++ - 模板类 -> 静态函数 -> 静态函数指针的链接错误
【发布时间】:2016-12-28 08:51:38
【问题描述】:

波纹管代码在 Visual Studio 和 Solaris 编译器上编译成功。但是在 g++ (SUSE Linux) 4.3.4 出现链接错误。请让我知道如何在 linux 上修复此链接错误? 注意:为了让代码更简洁明了,我在这里输入了代理代码。

//---------------- a1.h -----------

#ifndef __a1_h__
#define __a1_h__

#include <iostream>
#include <memory>

namespace ServiceManagement
{
    template <typename T>
    class ClassA1
    {
    public:
        ClassA1() {}

        typedef std::auto_ptr<T>(*addFunc)(int, int);
        static void setAddFunc(addFunc f)
        {
            s_AddFunc = f;
        }

    private:
        static addFunc s_AddFunc;
    };
}

#endif

//---------------- b1.h -----------

#ifndef __b11_h__
#define __b11_h__

#include "a1.h"

typedef ServiceManagement::ClassA1<int> setPosType;

namespace ServiceManagement
{
    class ClassB1
    {
    public:
        ClassB1() {}

        static void Register();
    private:
        std::auto_ptr<setPosType> m_ptrMsg;
    };

}

#endif

//---------------- b1.cpp -----------

#include "b1.h"

#include <iostream>
using namespace std;

//setPosType::addFunc setPosType::s_AddFunc;
template <> setPosType::addFunc setPosType::s_AddFunc;

namespace AA
{
    namespace v2
    {
        std::auto_ptr<int> message2_(int a, int b)
        {
            int c = a + b;

            std::auto_ptr<int> p1(new int);
            *p1.get() = c;

            return p1;
        }
    }
}

namespace ServiceManagement
{

    void ClassB1::Register()
    {
        setPosType::addFunc f1 = ::AA::v2::message2_;

        setPosType::setAddFunc(f1);
    }
}

int main()
{

    int  i = 0;
    cin >> i;
    return 0;
}

链接错误: /usr/bin/c++ -pthread -g -w -W -Wall -Wno-long-long -g -ldl -lm -lnsl -m64 -o -pthread -std=gnu++0x -Bdynamic

.. 构建“ CMakeFiles/templateTest.dir/b1.cpp.o -o ../../../../../..//templateTest -rdynamic CMakeFiles/templateTest.dir/b1.cpp.o: 在函数**ServiceManagement::ClassA1<int>::setAddFunc(std::auto_ptr<int> (*)(int, int))'**: /templateTest/**a1.h:18: undefined reference toServiceManagement::ClassA1::s_AddFunc' collect2: ld 返回 1 个退出状态**

注意 2: 已经在 b1.cpp 中定义了静态变量,如下所示, 模板 setPosType::addFunc setPosType::s_AddFunc;

【问题讨论】:

  • 您的问题的格式有些混乱,我无法确定错误日志的开头或结尾。您可以编辑它并为内联代码使用反引号(```)并为(html-escaped)输出使用&lt;pre&gt;&lt;/pre&gt; 吗?

标签: c++ linux templates function-pointers


【解决方案1】:

1.) 一旦初始化成员变量,它就可以工作:

template <> setPosType::addFunc setPosType::s_AddFunc = 0;

显然,如果没有初始化器,这一行是声明而不是定义,但老实说,我不明白为什么。

2.) Clang 告诉我,在其命名空间之外定义静态成员是 C++11 扩展。更好用

namespace ServiceManagement {
   template <> setPosType::addFunc setPosType::s_AddFunc = 0;
}

【讨论】:

  • 我已经使用了这段代码,但仍然出现同样的链接错误。
  • 我已经试过了。一旦初始化成员变量,它就可以工作:template &lt;&gt; setPosType::addFunc setPosType::s_AddFunc = 0; 我会更新我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多