Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-member static templated method definitions in C++?

Can I call a non-member static templated function from a static member function where the definition is split into header and cpp:

// zero.cpp

class Zero
{
    static void zero() { one(5); }
};

// one.h

template <typename T>
static void one(T& var);

// one.cpp

template <typename T>
void one(T& var) { }

// main.cpp

...

Zero::zero()

...

I'm having problems getting this to link, I keep getting undefined reference to the function I'm trying to define in one.cpp.

Initially I thought it was due to a problem with namespacing, but all files are now in the same namespace. Am I doing anything fundamentally wrong here?

like image 401
Dan Avatar asked Dec 30 '25 11:12

Dan


2 Answers

Template definitions need to be visible at the point of instantiation. That is, it needs to be in the header somehow:

// one.hpp

template <typename T>
static void one(T& var)
{
    // definition visible in header
}

Though I'm not sure why you'd want it to be static.

like image 194
GManNickG Avatar answered Jan 01 '26 02:01

GManNickG


As an addition to GMan's answer I would like to note that you can't make T& bind to an rvalue such as the integral literal 5 which is of type int. 5 will not bind to int&, but will bind to const int&.

like image 34
Armen Tsirunyan Avatar answered Jan 01 '26 01:01

Armen Tsirunyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!