0

i have a problem with my singleton template class.. i got this problem and searched for like 4 hours or more for a solution but i dont understand why it doesnt work because i declared get_instance() in the header file and in the source file

sorry for my bad english and if its an duplicate but the other thread doesnt help me at all.

hope you can help me. thank you in advance

Fehler    LNK2001    Nicht aufgelöstes externes Symbol ""public: static class common::config_t & __cdecl common::singleton_t<class common::config_t>::get_instance(void)" (?get_instance@?$singleton_t@Vconfig_t@common@@@common@@SAAAVconfig_t@2@XZ)".    

Fehler    LNK1120    1 nicht aufgelöste Externe

singleton.hpp

#ifndef SINGLETON_H
#define SINGLETON_H

#include <iostream>
#include <cstdint>

namespace common {
    template <typename T>
    class singleton_t{
    public:
        static T& get_instance();

        singleton_t(const singleton_t&) = delete;
        singleton_t& operator= (const singleton_t) = delete;

    protected:
        singleton_t() {}
    };

}

#endif // !SINGLETON_H

singleton.cpp

#include "stdafx.h"
#include "singleton.hpp"

namespace common {
    template<typename T>
    T& singleton_t<T>::get_instance()
    {
        static T instance;
        return instance;
    }
}

config.hpp

#ifndef CONFIG_H
#define CONFIG_H

#include <cstdint>

#include "singleton.hpp"

namespace common {
    class config_t : public singleton_t<config_t> {
        friend class singleton_t<config_t>;
    public:
        config_t();
        ~config_t();
    public:
        uint32_t variable_to_do_anything;
    };
}

//#define CONFIG common::config_t::get_instance()

#endif // !CONFIG_H

config.cpp

#include "stdafx.h"
#include "config.hpp"

namespace common {
    config_t::config_t() : variable_to_do_anything(1){

    }

    config_t::~config_t() {

    }
}

and i am trying to get it like this

        auto& config = common::config_t::get_instance();
        config.variable_to_do_anything;
тx-mem
  • 1
  • 3
  • singleton.cpp does not produce any code, your template function should be in a header file so it can be declared and later instantiated when you use it. – Jaffa Mar 09 '20 at 14:08
  • there should be no difference between the current way (header and source) and all in header. I tried it but i still get the same errors. – тx-mem Mar 09 '20 at 14:20
  • 1
    Read [this post](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). Your code inside the source file is not available from anywhere else, as it is just a declaration. You need the template declaration available to be able to instantiate it in another translation unit. – Jaffa Mar 09 '20 at 14:25
  • ok my bad. thank you :) – тx-mem Mar 09 '20 at 14:31

0 Answers0