Home > Mobile >  Template specialization in other project
Template specialization in other project

Time:12-23

I have C 17 project with the following project layout:

src/
  Common/
  Main/

In Common I have template function for deserization

namespace Common
{
  template <class T>
  T FromJson(std::string_view json)
}

In Main I want to have specialzation for only Main accessible type Config. How can I do that?

I tried this (Main/example.cpp):

#include "Common/Serialzation.hpp"
#include "Config.hpp"

namespace 
{
  template <>
  Main::Config Common::FromJson(std::string_view json) { 
     // use of other FromJson<T> specializations 
  }
}

/* other code that use FromJson<Main::Config> */

But this fails.

To fix it, I changed function name (following code works fine):

#include "Common/Serialzation.hpp"
#include "Config.hpp"

namespace 
{
  Main::Config LoadFromJson(std::string_view json) { 
    // Common::FromJson is used here fine, no compile errors 
  }
}

/* other code that use FromJson<Main::Config> */

But this solution is very bad for me.

CodePudding user response:

As already pointed out in a comment, you need to specialize the template function in the same namespace where it was declared.

See for example following code:

#include <iostream>

namespace Common {
template <typename U>
void print(U u) { std::cout << "general " << u << std::endl; }

}

namespace Main {
    struct A { int x; };

}

namespace Common {

template <>
void print(Main::A i) { std::cout << "specialization " << i.x << std::endl; }

}

int main()
{
    Common::print('c');
    Common::print(Main::A{1});

}
  • Related