vendredi 24 juillet 2020

is it possible to use Template with enable_if<> in the cpp file or i'm really pushing it?

Problem Description

I was reading in the following page How to Define a Template Class in a .h File and Implement it in a .cpp File that we can indeed implement a template function in cpp. And that's what I did for the function getTemplate(T Compare). I added the declaration in the cpp file: template int Test::getTemplate<std::greater<int>>(std::greater<int>);. So At the moment I have no linker problems for getTemplate(T Compare).

I was wondering is it possible to implement getValue in the cpp? I am trying to add the declaration just like what I did getTemplate(T Compare). I added the following declaration

template<typename Compare>
int Test::getValue<std::greater<int>>(int x, int y, std::greater<int>, typename std::enable_if<std::is_same<Compare, std::greater<int> >::value, void>::type * );

But it's like a cat chasing its tail


Working Source Code

#pragma once

#include <type_traits>
#include <functional>

class Test {
  public:
   Test();
   template<typename Compare>
   int getValue(int x, int y, Compare compare, typename std::enable_if<std::is_same<Compare, std::greater<int> >::value, void>::type * = nullptr);

   template<typename T>
   int getTemplate(T Compare);
};

    #include "test.h"
    
    Test::Test() {}
    
    template<typename Compare>
    int Test::getValue(int x, int y, Compare compare, typename std::enable_if<std::is_same<Compare, std::greater<int> >::value, void>::type * ) {
         return 1;
       }
    
    template<typename T>
    int Test::getTemplate(T Compare) {
      return std::min(1,2,Compare);
    }
    
   ///The associated class member functions will be available atlink time
    template int Test::getTemplate<std::greater<int>>(std::greater<int>);
    

#include <iostream>
#include "test.h"

int main() {
  Test t;
  std::cout << t.getTemplate(std::greater<int>()) << std::endl;
}

Aucun commentaire:

Enregistrer un commentaire