Specialized Specialized Function: Linker Error

I am trying to specialize the function of two template arguments when the types of the template arguments are the same. I do it as follows:

#include <iostream>
#include <type_traits>

using namespace std;

template<typename U, typename T>
int fun( U& u, T t );

template<>
inline
int fun( int& u, float t )
{
    cout << "int, float" << endl;
    return 0;
}

template<typename U, typename T>
inline
int fun( U& u, typename std::enable_if<std::is_same<U, T>::value ,T>::type t )
{
    cout << "U == T" << endl;
    return 0;
}

int main()
{
    int a;
    float b1, b2;

    fun(a, b1);
    fun(b1, b2);

    return 0;
}

This code compiles fine (GCC 4.8.2), but the linker gives undefined references to all calls funwhen Uthey Tare the same type. Why is this not working?


Linker Output :

g++ -std=c++11 test.cpp

/tmp/cc7HWboz.o: In function `main':
test.cpp:(.text+0x66): undefined reference to `int fun<float, float>(float&, float)'
collect2: error: ld returned 1 exit status
+4
source share
1 answer

PROBLEM

fun, std::enable_if , , ; T.

, fun b1 b2 , template<typename U, typename T> int fun( U& u, T t ), .. , .


, , , .

template<
  typename U,
  typename T,
  typename = typename std::enable_if<std::is_same<U, T>::value>::type
>
inline int fun( U& u, T t)
{
    cout << "U == T" << endl;
    return 0;
}

inline int fun( int& u, float t )
{
    cout << "int, float" << endl;
    return 0;
}

T, U , ; ++ , int&, float , U&, T.

+5

Source: https://habr.com/ru/post/1541968/


All Articles