C++ 使用类声明之外的实现启用\u if方法专门化
我正在编写一个模板化的单例超类,它可以提供线程本地实例或进程全局实例。下面的代码编译并在技术上符合我的需要。 但是,如何在类声明之外编写函数实现呢?如何在类中声明函数(注释行是否正确) 所有类似的问题都实现了类声明中的函数C++ 使用类声明之外的实现启用\u if方法专门化,c++,templates,C++,Templates,我正在编写一个模板化的单例超类,它可以提供线程本地实例或进程全局实例。下面的代码编译并在技术上符合我的需要。 但是,如何在类声明之外编写函数实现呢?如何在类中声明函数(注释行是否正确) 所有类似的问题都实现了类声明中的函数 #include <vector> #include <type_traits> using namespace std; template <class t, bool tls=true> class A{ public: ty
#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;
}
#包括
#包括
使用名称空间std;
模板
甲级{
公众:
typedef std::向量向量向量向量;
//静态Avector&getVector();
模板
静态Avector&
getVector(){
静态Avector v=Avector();
返回v;
}
模板
静态Avector&
getVector(){
静态线程_local Avector v=Avector();
返回v;
}
};
int main(){
向量&vi=A::getVector();
向量&vd=A::getVector();
返回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;
}
模板
结构A
{
typedef std::向量向量向量向量;
静态Avector&getVector();
};
模板
typename A::Avector&A::getVector()
{
线程\本地类型名A::Avector v;
返回v;
}
模板
甲级
{
typedef std::向量向量向量向量;
静态Avector&getVector();
};
模板
typename A::Avector&A::getVector()
{
静态类型名A::Avector v;
返回v;
}
另外,通常在TLS bool上不使用SFINAE,只需直接使用bool并专门化true和false即可。@rubenvb您不能部分专门化函数,尽管从上面的代码中,我看不出为什么函数是模板正确的,然后您可以像在回答中一样使用helper结构;)在本例中使用SFINAE的优点是,我可以对线程本地实例和每个进程实例使用相同的类A。发布的代码只是一个最小的复制器。我的应用程序中的实际类A提供了更多的方法。我的问题是,如何在类声明之外实现函数。这个答案再次实现了声明中的函数。此外,我的真实代码有更多的函数,通过上述方法,我可以避免代码重复。@Joachim你是说在类之外定义方法的语法是什么?是的,我在类声明之外的代码中找不到定义方法的语法。