我正在尝试找到一种方法来处理一些遗留代码。有一个模板化类,我想专门化构造函数以在使用特定参数实例化时将不同的参数传递给它的基类。
template<typename T, typename U>
class A : public U {
public:
A(T &t, bool b);
// Other member functions
}
template<typename T, typename U>
A<T, U>::A(T &t, bool b)
: U(t, b) {}
当 U
属于某个(模板化的)类时,我需要更改此构造函数的行为。
template<typename Z>
class S;
template<typename T>
template<typename Z>
A<T, S<Z>>::A(T &t, bool b)
: S<Z>(t, b, false) {}
这可能吗?我知道如果不重新定义一个新类,就无法完成类模板特化。但我宁愿只专门化此行为,而不是此类 U
的任何其他成员函数。
最佳答案
C++11 解决方案可以基于 SFINAE:如果 U
则启用第一个或第二个构造函数是 S
是否基于类型。
为了做到这一点,开发一个类型特征来检测一个类型是否是(或不是)S
是很有用的。基于;举例说明
template <typename>
struct isS : public std::false_type
{ };
template <typename T>
struct isS<S<T>> : public std::true_type
{ };
与 isS
,您可以如下编写构造函数(在 A
类的主体中)
template <typename V = U>
A(T & t, bool b,
typename std::enable_if<false == isS<V>::value>::type * = nullptr )
: U(t, b)
{ std::cout << "generic A constructor" << std::endl; }
template <typename V = U>
A(T & t, bool b,
typename std::enable_if<true == isS<V>::value>::type * = nullptr)
: U(t, b, false)
{ std::cout << "S specific A constructor" << std::endl; }
如果你需要 S
的模板参数, 您可以定义 isS
的特化如下
template <typename T>
struct isS<S<T>> : public std::true_type
{ using type = T; };
并将其用作 typename isS<V>::type
.
一个完整的工作示例
#include <vector>
#include <iostream>
#include <type_traits>
template <typename T>
struct S
{
S (T const &, bool, bool)
{ std::cout << "S constructor" << std::endl; }
};
template <typename>
struct isS : public std::false_type
{ };
template <typename T>
struct isS<S<T>> : public std::true_type
{ };
template <typename T, typename U>
struct A : public U
{
template <typename V = U>
A(T & t, bool b,
typename std::enable_if<false == isS<V>::value>::type * = nullptr )
: U(t, b)
{ std::cout << "generic A constructor" << std::endl; }
template <typename V = U>
A(T & t, bool b,
typename std::enable_if<true == isS<V>::value>::type * = nullptr)
: U(t, b, false)
{ std::cout << "S specific A constructor" << std::endl; }
};
int main ()
{
long l { 0L };
// print "generic A constructor"
A<long, std::vector<int>> alv(l, true);
// print "S constructor>" and "S specific A constructor"
A<long, S<int>> als(l, true);
}
关于c++ - 在模板化模板参数上专门化模板类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45239475/