我有以下代码:
#include <iostream>
#include <type_traits>
using namespace std;
template<typename T, int N>
class A {
public:
static constexpr int n = N;
};
template<typename T, typename X, int N>
class B {
public:
static constexpr int x = N;
};
template<typename T>
void test(T) {
if constexpr (std::is_same_v<T, A>) {
int a = T::n;
} else if constexpr (std::is_same_v<T, B>) {
int a = T::x;
}
cout << "a";
};
int main()
{
A<int, 2> a;
test(a);
return 0;
}
编译它会产生以下错误:
error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Tp, class _Up> constexpr const bool std::is_same_v<_Tp, _Up>’
20 | if constexpr (std::is_same_v<T, A>) {
| ~~~~~^~~~~~~~~~~~~~~
note: expected a type, got ‘A’
问题是我无法在此处使用正确的类型(如A),因为我不知道模板参数是什么或有多少。基本上,我想将任何类型的A类与任何模板参数进行匹配。
您需要为此编写自己的特征:
template<typename>
struct is_specialization_of_A : std::false_type {};
template<typename T, int N>
struct is_specialization_of_A<A<T,N>> : std::true_type {};
template<typename T>
inline constexpr auto is_specialization_of_A_v = is_specialization_of_A<T>::value;
并且类似地表示B
。
您也可以将模板用作特征的模板模板参数,因此您只需要一个特征定义,但是仅在模板的模板参数类别匹配时才有效。这里不是这种情况(A
具有<type, int>
,而B
具有<type, type, int>
)。