pseyfert
pseyfert

Reputation: 3613

linker error with templated friend function of templated class when using template independent enable_if

I'm dealing with a templated class with a templated friend function

template<typename T>
struct X {
  template<typename someX>
  auto friend f (someX x) -> std::enable_if_t<std::is_same_v<decltype(x.hidden), int>, int>;

private:
  T hidden = 42;
};

template<typename someX>
auto f(someX x) -> std::enable_if_t<std::is_same_v<decltype(x.hidden), int>, int> {return x.hidden;}

this compiles fine with g++, but fails at link time in

int main () {
  X<int> x;
  std::cout << f(x);
}

with

prog.cc:(.text+0x15): undefined reference to `std::enable_if<is_same_v<decltype ({parm#1}.hidden), int>, int>::type f<X<int> >(X<int>)'
collect2: error: ld returned 1 exit status

see here.

What I observed is:

is this a g++ (8.2) bug or does clang++ violate the standard, and in the latter case, how do I trigger the code generation for the function?

Upvotes: 1

Views: 97

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69882

is this a g++ (8.2) bug or does clang++ violate the standard

I suspect gcc is correct. Template friends are a dark corner of the language.

how do I trigger the code generation for the function?

I'd do it via a befriended actor.

#include <iostream>

struct friend_of_f
{
    template<class someX> 
    static auto apply(someX x) -> std::enable_if_t<std::is_same_v<decltype(x.hidden), int>, decltype(x.hidden)>
    {
        return x.hidden;
    }
};

template<typename someX>
auto f(someX x) -> decltype(friend_of_f::apply(x))
{
    return friend_of_f::apply(x);
}

template<typename T>
struct X 
{

friend friend_of_f;

private:
  T hidden = 42;
};




int main () {
  X<int> x;
  std::cout << f(x);
  X<double> y;
//  std::cout << f(y);
}

Upvotes: 1

Related Questions