I am having trouble getting an inline method implementation to reference a generic template instance method [ check nomenclature ] because I don't know how to refer to it (or can't). I can make it work inline, but want to know if/how to do defer the definition.
I've found similar questions with the same setup (class/struct template parameter and a method instance parameter), but they are always solving a different problem (I think).
#include <functional>
template <typename T>
struct Vec {
T elem;
Vec(T t) : elem(t) { }
// this works, but I want to defer the definition to later
template <typename R>
Vec<R> fmap(std::function<R(T)> apply) const {
return Vec<R>(apply(elem));
}
// but I want to defer the definition to later in the file
// template <typename R>
// Vec<R> fmap2(std::function<R(T)> apply) const;
};
// This FAILS: how do I refer to this?
// template <typename T,typename R>
// inline Vec<R> Vec<T>::fmap2(std::function<R(T)> apply) const {
// return Vec<R>();
// }
Uncommenting fmap2
on GCC gives.
no declaration matches ‘Vec<R> Vec<T>::fmap2(std::function<R(T)>) const’
Visual Studio 2019 gives
unable to match function definition to an existing declaration
The inline definition works, but I want to define that templated member later in the compilation unit if possible.
Thanks in advance.
CodePudding user response:
You need to declare typename T
for Vec
first, and then typename R
for fmap2
, like this
template <typename T>
template <typename R>
Vec<R> Vec<T>::fmap2(std::function<R(T)> apply) const {
return Vec<R>();
}