gpt4 book ai didi

c++ - 基于嵌套的内部参数专门化模板

转载 作者:太空宇宙 更新时间:2023-11-04 12:13:04 26 4
gpt4 key购买 nike

我想根据模板的内部参数专门化模板。我正在使用非严格的评估,这让事情变得困难。

特化应该基于最少嵌套的模式匹配。例如:

template<typename T>
struct data1;

template<typename T>
struct fun1 {
using type = data1<T>;
};

template<typename T>
struct fun2;
template<typename T>
struct fun2<data1<T>> {
using type = data1<T>;
};

fun2<data1<int>> x1; // this works as expected, T=int
fun2<data1<fun1<int>>>::type x2; // this works as expected, T=fun1<int>
fun2<fun1<int>>::type x3; // this should be specialized as fun2<data1<int>>, T=int
fun2<fun2<fun1<int>>>::type x4; // this should be specialized as fun2<data1<int>>, T=int

我该怎么做?

最佳答案

您可以只使用模板模板参数:

template<typename T>
struct data1;

template<typename T>
struct fun1 {
using type = data1<T>;
};

template<typename T>
struct fun2;

template<class T>
struct fun2<data1<T>>{
using type = data1<T>;
};

template<template<class> class X, class T>
struct fun2<X<T>>
: fun2<typename X<T>::type>{};

测试:

#include <type_traits>

static_assert(std::is_same<fun2<data1<int>>::type, data1<int>>::value, "fun2<data1<int>>");
static_assert(std::is_same<fun2<data1<fun1<int>>>::type, data1<fun1<int>>>::value, "fun2<data1<fun1<int>>>");
static_assert(std::is_same<fun2<fun1<int>>::type, data1<int>>::value, "fun2<fun1<int>>");
static_assert(std::is_same<fun2<fun2<fun1<int>>>::type, data1<int>>::value, "fun2<fun2<fun1<int>>>");

int main(){
}

Live example on Ideone (with using-aliases changed to typedefs) .

关于c++ - 基于嵌套的内部参数专门化模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9010905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com