I have a class A
that is a template, and I want to specialize the method foo()
if the class is a std::vector<T>
with T
generic, I am getting the error: invalid use of incomplete type. I'd like to avoid writing all specializations for all possible vectors.
#include <iostream>
#include <vector>
template<typename V>
struct A {
void foo() {
std::cout << "A<V>\n";
}
};
template<typename T>
void A<std::vector<T>>::foo() {
std::cout << "A<V<T>>\n";
}
int main() {
C<int> a;
C<std::vector<int>> b;
return 0;
}
Just using c++20 contrians:
template <typename V>
struct A {
void foo() { std::cout << "A<V>\n"; }
void foo() requires (std::same_as<V, std::vector<typename V::value_type>>) {
std::cout << "A<V<T>>\n";
}
};
Then this works:
A<int>{}.foo(); // call normal one
A<std::vector<int>>{}.foo(); // call specialized one