c++ - 在类声明之外实现的 enable_if 方法特化

标签 c++ templates

我正在编写一个模板化的单例父类(super class),它可以提供一个线程局部实例或一个进程全局实例。下面的代码编译并在技术上符合我的需要。 但是,如何在类声明之外编写函数实现呢?我如何在类中声明函数(注释行是否正确)?

所有类似的问题都实现了类声明中的功能。

#include <vector>
#include <type_traits>


using namespace std;

template <class t, bool tls=true>
class A{
public:
  typedef std::vector<t> Avector;
//  static Avector& getVector();

  template <class T=t, bool TLS=tls, typename std::enable_if<!TLS>::type* = nullptr>
  static Avector&
  getVector(){
    static Avector v=Avector();
    return v;
  }

  template <class T=t, bool TLS=tls, typename std::enable_if<TLS>::type* = nullptr>
  static Avector&
  getVector(){
    static thread_local Avector v=Avector();
    return v;
  }
};

int main(){
  vector<int>& vi = A<int>::getVector();
  vector<double>& vd = A<double, false>::getVector();
  return 0;
}

最佳答案

你可以改写

template<typename T, bool>
struct A
{
    typedef std::vector<T> Avector;
    static Avector& getVector();
};

template<typename T, bool b>
typename A<T, b>::Avector& A<T, b>::getVector()
{
    thread_local typename A<T, true>::Avector v;
    return v;
}

template<typename T>
class A<T, false>
{
    typedef std::vector<T> Avector;
    static Avector& getVector();
};

template<typename T>
typename A<T, false>::Avector&  A<T, false>::getVector()
{
    static typename A<T, false>::Avector v;
    return v;
}

另外,一般singletons shouldn't be used

关于c++ - 在类声明之外实现的 enable_if 方法特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44459464/

相关文章:

c++ - 在同一个 C++ 源文件中使用多个命名空间是一种好习惯吗?

c++ - Facebook 拼图错误 : throws it's automated mail regarding build/run error

c++ - 通过模板滥用的函数式 C++

php - Symfony2命令行生成全局文件夹下的twig模板

c++ - 将 Sprite 旋转到鼠标位置

c++ - A* bug(A星搜索算法)

c++ - 在 gtk 中绘制点/线。 C++

c++ - 模板类方法特化

c++ - 在 C++11 中,是否可以将模板函数包装在 std::function 中?

java - 配置 Velocity 以读取类路径之外的模板文件