0

I want to create a method where I have a variable argument type. I'm writing a library that needs to have this because you can't be certain which type of object a user wants to use.

It's a method that serializes an object made with the Google ProtocolBuffer but the ProtocolBuffer object can be of different types (the name can change).

Is this possible? I tried with this but it doesn't work:

template <class X>
void Base::Send(X data)
{
    // Serialize to string.
    std::string sendData;
    data.SerializeToString(&sendData);

    // Convert data to const char*
    const char* dataToSend = sendData.c_str();

    int iResult;
    iResult = send( ConnectSocket, dataToSend, (int)strlen(dataToSend), 0 );
    if (iResult == SOCKET_ERROR) 
    {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        exit(1);
    }
}
Dries
  • 995
  • 2
  • 16
  • 45
  • _'I tried with this but it doesn't work'_ What in particular didn't work? – πάντα ῥεῖ Apr 23 '14 at 13:29
  • `data.SerializeToString(&sendData);` is probably wrong. AFAIR this method takes a `std::string&` not a `std::string*`! – πάντα ῥεῖ Apr 23 '14 at 13:30
  • Well, I call this method in the app that uses my library (that holds the code above) and it returns: `error LNK2019: unresolved external symbol "public: void __thiscall NetworkingLib::Base::Send(class data::Data)" (??$Send@VData@data@@@Base@NetworkingLib@@QAEXVData@data@@@Z) referenced in function "private: void __thiscall Scene::SendPlayerData(void)" (?SendPlayerData@Scene@@AAEXXZ)` – Dries Apr 23 '14 at 13:30
  • SerializeToString(&sendData) does work. I tried it before implementing here – Dries Apr 23 '14 at 13:31
  • You are also aware you cannot implement templates in separate compilation units? – πάντα ῥεῖ Apr 23 '14 at 13:31
  • No I'm not. This is the first time I'm trying to use templates (since I think that's the right thing to use) – Dries Apr 23 '14 at 13:32
  • Please put all the implementation code into the same header where the template is declared. Non templated implementation code of your class, can still be placed into separate compilation units. But usually you would make your whole class a template. – πάντα ῥεῖ Apr 23 '14 at 13:34
  • Also `strlen(dataToSend)` is surely not what you want, protobuf doesn't serialize the data to a c-style string! You want to use e.g. `ByteSize()` to determine the serialized length of the data. – πάντα ῥεῖ Apr 23 '14 at 13:38
  • Ok I'll change that. As for now, your help seems to have done it! Thanks again – Dries Apr 23 '14 at 13:41
  • possible duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Jarod42 Apr 23 '14 at 14:43

0 Answers0