【问题标题】:C++ Template specialization of member function with a generic type eg. std::vector<T> do not compile具有泛型类型的成员函数的 C++ 模板特化,例如。 std::vector<T> 不编译
【发布时间】:2021-11-30 22:12:14
【问题描述】:

我对泛型结构的成员函数的特化有疑问。

我的目标是使用各种 std::vector 专门化 Bar 的成员函数 Run。

#include <iostream>
#include <vector>

// (1) compile
template <typename T> 
struct Foo {
  T Run() { 
    std::cout << "Foo not specialized" << std::endl; 
    return T();
  };
};

// (2) compile
template <typename T> 
struct Foo<std::vector<T>> {
  std::vector<T> Run() { 
    std::cout << "Foo specialized" << std::endl;  
    return std::vector<T>();
   };
};


template <typename T> struct Bar
{
    T Run();
};

// (3) compiles
template<typename T>
T Bar<T>::Run() {
    std::cout << "Bar not specialized" << std::endl;
    return T();
};

// (3) compiles
template<>
std::vector<bool> Bar<std::vector<bool>>::Run() {
    std::cout << "Bar specialized" << std::endl;
    return std::vector<bool>();
};

// (4) wont compile: error: invalid use of incomplete type 'struct Bar<std::vector<T> >
template<typename T>
std::vector<T> Bar<std::vector<T>>::Run() {
    std::cout << "Bar specialized" << std::endl;
    return std::vector<T>();
};

int main(int argc, char const *argv[]) {
  Foo<bool> f1;
  bool rf1 = f1.Run();

  Foo<std::vector<int>> f2;
  std::vector<int> rf2 = f2.Run();

  Bar<bool> b1;
  bool rb1 = b1.Run();

  Bar<std::vector<bool>> b2;
  std::vector<bool> rb2 = b2.Run();

  Bar<std::vector<int>> b3;
  std::vector<int> rb3 = b3.Run();

  return 0;
};

如果我将其注释掉,它可能无法编译参见 (4)。 有没有办法让这个工作。提前谢谢你。

Demo not compiling

Demo compiling

【问题讨论】:

    标签: c++ templates generics template-specialization


    【解决方案1】:

    模板函数不能是部分特化的。

    你可以用蹦床和超载来做到这一点。喜欢Run(){ DoRun(*this) 然后写DoRun 重载。

    【讨论】:

    • 或者,可以在模板类中调用(静态)函数并对该类进行部分特化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 2015-05-03
    • 2018-06-02
    • 1970-01-01
    相关资源
    最近更新 更多