我希望实现函数is_type_of_v,能够识别类型技能的模板实例。请参阅下面源代码中的主要功能,以充分理解请求。用语言来解释比用代码来解释要难。
该解决方案在VS 2017中应该可以在c++17下工作。
#include <iostream>
#include <type_traits>
template<class T>
struct Base
{
private:
constexpr Base() = default;
friend T;
};
struct Derived1 : Base<Derived1>
{
};
struct Derived2 : Base<Derived2>
{
};
template<class T, class F, int... Ints>
struct Skill : T
{
};
int main()
{
Skill<Derived1, std::equal_to<int>, 1, 2> object1;
Skill<Derived2, std::equal_to<int>, 3> object2;
Derived1 other;
constexpr auto res1 = is_type_of_v<Skill, decltype(object1)>;//Must be true
constexpr auto res2 = is_type_of_v<Skill, decltype(object2)>;//Must be true
constexpr auto res3 = is_type_of_v<Skill, decltype(other)>;//Must be false
}发布于 2022-01-31 21:36:42
对于Skill,您可以将以下内容写成
template <template <typename, typename, auto...> class, typename>
struct is_type_of : public std::false_type
{};
template <template <typename, typename, auto...> class C,
typename T1, typename T2, auto ... Is>
struct is_type_of<C, C<T1, T2, Is...>> : public std::true_type
{};
template <template <typename, typename, auto...> class C, typename T>
constexpr auto is_type_of_v = is_type_of<C, T>::value;所以你可以证实
static_assert( true == is_type_of_v<Skill, decltype(object1)> );
static_assert( true == is_type_of_v<Skill, decltype(object2)> );
static_assert( false == is_type_of_v<Skill, decltype(other)> );不幸的是,此解决方案只适用于模板-模板参数接收两个类型名称,前,和一个不同的值列表后。
我不认为这是可能的(C++17,但也包括C++20),一个通用的模板-模板参数在第一位置的通用解决方案。
而在C++17之前(C++11和C++14)更糟糕,因为您不能将auto...用于值。
https://stackoverflow.com/questions/70932913
复制相似问题