我正在编写一个模板化的单例父类(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;
}
关于c++ - 在类声明之外实现的 enable_if 方法特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44459464/