Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

c++ - Is it possible to specialize a method of a template class on another templated class?

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>
";
  }
};

template<typename T>
void A<std::vector<T>>::foo() {
  std::cout << "A<V<T>>
";
}

int main() {
  C<int> a;
  C<std::vector<int>> b;

  return 0;
}
question from:https://stackoverflow.com/questions/65945454/is-it-possible-to-specialize-a-method-of-a-template-class-on-another-templated-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If foo() doesn't depends from other elements of A, you can inherit it through a base class and specialize the base class.

I mean something as follows

template <typename>
struct Base
 { void foo() { std::cout << "A<V>
"; } };

template <typename ... Ts>
struct Base<std::vector<Ts...>>
 { void foo() { std::cout << "A<V<Ts...>>
"; } };

template <typename T>
struct A : public Base<T>
 { };

Another possible solution is tag-dispatching: develop two foo() functions an "enable" the correct one, according the needs.

For example

template <typename>
struct is_vector : public std::false_type
 { };

template <typename ... Ts>
struct is_vector<std::vector<Ts...>> : public std::true_type
 { };

template <typename T>
struct A
 {
   void foo (std::true_type) { std::cout << "A<V<Ts...>>
"; }

   void foo (std::false_type) { std::cout << "A<V>
"; }

   void foo () { foo(is_vector<T>{}); } 
 };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...