0
#include <iostream>
#include <fstream>
#include <type_traits>
#include <Windows.h>

#include "abase.h"

using namespace std;    
class Storage {
    string _path;

public:
    Storage(string path);
    ~Storage() = default;
    template <typename T >
        bool writeFile(string fileName, 
            typename enable_if<is_base_of<ABase, T>::value, T >::type* data);
}

Definition...

 #include "storage.h"

Storage::Storage(string path)
{
    this->_path = path;
}
template <typename T >
        bool Storage::writeFile(string fileName, 
            typename enable_if<is_base_of<ABase, T>::value, T >::type* data){
       return true;
}

Im still getting error by Linker:

LNK2019 unresolved external symbol "public: bool __thiscall Storage::writeFile(class std::basic_string,class std::allocator >,class AFile*)" (??$writeFile@VAFile@@@Storage@@QAE_NV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAVAFile@@@Z) referenced in function _main

Why am i getting it if code is looking right. Its generic definition of method in a class and Im trying to constrain class type passing to the method. And the AFile is inherited from ABase.

ABase is abstract class.

Simple usage in main:

Storage* s = new Storage("C:\\aPath...");
AFile* afile = new AFile();
s->writeFile<AFile>("a.txt", afile);
Emil Mein
  • 33
  • 1
  • 5
  • s = is object of Storage – Emil Mein Dec 04 '17 at 22:07
  • Um... Firstly, The error message says that the function is actually a class member (a member of class `Storage`). But neither your declaration nor your definition defines it as a class member. How come? Secondly, how does that qualify as "usage"? I don't see any mention of `writeFile` in your "usage". – AnT stands with Russia Dec 04 '17 at 22:11
  • Updated question. All what I have done... – Emil Mein Dec 04 '17 at 22:37
  • Possible duplicate of [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – AnT stands with Russia Dec 04 '17 at 22:38
  • I could be but what if I want to just template one method of a class and not whole class then ? Becouse I want do it just this way. – Emil Mein Dec 04 '17 at 22:55
  • There's nothing wrong with "templating just one method of a class". However, that does not change what is said at the link I posted. You have to define your method in the header file. – AnT stands with Russia Dec 04 '17 at 23:10

1 Answers1

0

To solve your linking error you can explicitly instantiate[1] your template member function in the Storage.cpp like this:

template
bool Storage::writeFile<AFile>(string fileName,
    enable_if<is_base_of<ABase, AFile>::value, AFile>::type* data);

so the compiler creates the function and the linker can find.

It's better to move the definitions in the header file - Why can templates only be implemented in the header file?.

Mihayl
  • 3,821
  • 2
  • 13
  • 32