I am trying to specify a template member function of a template class out of the class' context. Is it possible? (I understand that it is possible within the class context but I'd like to separate from the class' body)
template<typename T1>
class A
{
public:
template<typename T2>
constexpr bool test(T2 _)
{
return false; // imagine this is Unimplemented exception
}
};
template<typename T1>
template<>
constexpr bool A<T1>::test<char>(char _) // <- this is not compiling
{
return true; // imagine this is custom behavior for A<T1>::test<char>
}
int main() {
A<int> test_var;
static_assert(test_var.test<char>('a'), "Not working");
static_assert(test_var.test<int>(5) == false, "Not working");
return 0;
}
The compilation error from x86-64 gcc 12.2 -std=c++20 -O2 is:
<source>:13:10: error: invalid explicit specialization before '>' token
13 | template<>
| ^
<source>:13:10: error: enclosing class templates are not explicitly specialized
<source>: In function 'int main()':
<source>:21:38: error: static assertion failed: Not working
21 | static_assert(test_var.test<char>('a'), "Not working");
|
Tested via: https://godbolt.org/z/rToMEYYbc
A few things I tried were:
template<typename T1>
template<>
constexpr bool A<T1>::test<char>(char _) // <- this is not compiling
{
return true; // imagine this is custom behavior for A<T1>::test<char>
}
template<typename T1>
constexpr bool A<T1>::test<char>(char _) // <- this is not compiling
{
return true; // imagine this is custom behavior for A<T1>::test<char>
}
template<typename T1>
template<typename>
constexpr bool A<T1>::test<char>(char _) // <- this is not compiling
{
return true; // imagine this is custom behavior for A<T1>::test<char>
}
template<typename T1>
template<typename T2=char>
constexpr bool A<T1>::test(T2 _)
{
return true;
}
template<typename T1>
template<typename T2=char>
constexpr bool A<T1>::test(char _)
{
return true;
}
template<typename T1>
template<typename T2=char>
constexpr bool A<T1>::test<T2>(T2 _)
{
return true;
}
No success with any of those.