无法用模板参数替换模板模板参数

问题描述 投票:0回答:1

我有一个像这样的模板化结构:

template<int Min, int Max>
struct TInt
{
    int Get() const { return StoredVal; }
    TInt& operator=(int Val) { StoredVal = FMath::Clamp(Val, Min, Max); return *this; }
    bool WithinRange(int Val) const { return Min <= Val && Val <= Max; }

private:
    int StoredVal = Min;
};

阅读完此提案后,尝试创建这些模板来检查类型是否是

TInt
的模板专业化:

template<class T, template<class...> class Primary>
struct is_specialization_of : std::false_type {};

template<template<class...> class Primary, class... Args>
struct is_specialization_of<Primary<Args...>, Primary> : std::true_type {};

template<class T, template<class...> class Primary>
inline constexpr bool is_specialization_of_v = is_specialization_of<T, Primary>::value;

这就是我尝试使用它的方式:

template<typename T>
struct IsValidType { static constexpr bool Value = is_specialization_of<T, TInt>; };

但我不断收到此错误:

"Cannot substitute template argument TInt for template template parameter Primary"
。我已经检查并尝试了类似问题的其他答案,但似乎没有什么对我有用。

我并不真正关心general情况(可变模板),只要两个模板参数,如果我能做到这一点,这也将增加我的学习。

我需要做什么才能使这项工作成功?

c++ c++20
1个回答
0
投票

问题是:

template<class T, template<class...> class Primary>
struct is_specialization_of : std::false_type {};

is_specialization_of
采用
template <class...> class Primary
的形式。接受一定数量的 type 模板参数的类模板。但是
TInt
不接受 type 模板参数,它接受 non-type 模板参数(特别是两个
int
)。今天的 C++ 中无法正确编写
is_specialization_of


但是,如果您只想编写一个特定的特征来检查某物是否是

TInt
,那么使用变量模板会更简单:

template <class T>
inline constexpr bool is_tint = false;

template <int Min, int Max>
inline constexpr bool is_tint<TInt<Min, Max>> = true;

或者用需求表达式推到“一行”(ish):

template <class T>
concept is_tint = requires (T const& t){
    []<int Min, int Max>(TInt<Min, Max> const&){}(t);
};
© www.soinside.com 2019 - 2024. All rights reserved.