【发布时间】:2021-04-23 00:14:04
【问题描述】:
我有一个带有 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。
提前致谢!
【问题讨论】:
标签: c++ templates inheritance specialization