C ++ - 模板类 - >静态功能 - >静态函数指针的链接错误

时间:2016-12-28 08:51:39

标签: c++ linux templates function-pointers

Bellow代码在Visual studio& amp;成功编译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

.. build&#34; 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 to ServiceManagement :: ClassA1 :: s_AddFunc&#39; collect2:ld返回1退出状态**

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

1 个答案:

答案 0 :(得分:0)

1。)初始化成员变量后,它可以正常工作:

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

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

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

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