我有一个模板基类,其模板参数为 bool 类型。这个基类的构造函数参数列表取决于模板参数是真还是假。我想从此类派生另一个模板类,其模板参数是任何类型。我需要这个派生类根据该类型的特征调用该基类的正确构造函数。
下面的例子并不包罗万象。不管是否完整,基类模板 bool 都可以用于任何类型特征。此外,传递给派生类的模板参数的类型可以是任何类型。
我已经尝试了几种不同的方法来尝试用语法表达这个东西,但我得到的最接近的方法是使用下面的代码。然而,由于派生类需要完全专门化这一事实,它会出错。
#include <type_traits>
using namespace std;
template<bool IsIntegral> struct Base
{
template<bool IsI = IsIntegral,
typename I = typename enable_if<IsI>::type>
Base(int param) {}
template<bool IsI = IsIntegral,
typename I = typename enable_if<!IsI>::type>
Base() {}
};
template<class T> class CL :
Base<is_integral<T>::value>
{
public:
template<bool U = is_integral<T>::value> CL();
};
template<>
template<class T>
CL<T>::CL<true>() : // error: ISO C++ forbids declaration of ‘CL’ with no type [-fpermissive]
// CL<T>::CL<true>() :
// ^
// error: non-type partial specialization ‘CL<true>’ is not allowed
// error: no declaration matches ‘int CL<T>::CL()’
// CL<T>::CL<true>() :
// ^~~~~
Base(4) { }
template<>
template<class T>
CL<T>::CL<false>() // error: ISO C++ forbids declaration of ‘CL’ with no type [-fpermissive]
// CL<T>::CL<true>() :
// ^
// error: non-type partial specialization ‘CL<true>’ is not allowed
// error: no declaration matches ‘int CL<T>::CL()’
// CL<T>::CL<true>() :
// ^~~~~
{ }
int main () {
// Base<true> a; // won't compile as expected
Base<true> a(4);
// Base<false> b(4); // won't compile as expected
Base<false> b;
CL<int> c; // integral
CL<int*> d; // non-integral
// should work for any types other than int and int*
return 0;
}
我需要保持类型 T 的通用性,不能完全特化类 CL。正确的语法是什么?有解决方法吗?
我使用的是 gcc-g++ 版本 8.3.0-6。
提前致谢!
最佳答案
在玩弄这个之后,我想出了这个,我想它属于“变通办法”的范畴,您愿意考虑:
template<class T> class CL :
Base<is_integral<T>::value>
{
public:
CL() : CL{ is_integral<T>{} } {}
template<typename U=T>
CL(std::true_type) : Base<true>{4} {}
template<typename U=T>
CL(std::false_type)
{
}
};
关于c++ - 具有模板构造函数特化的模板类,用于初始化模板化基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65778909/