gpt4 book ai didi

c++ - 检查传递给可变参数模板的类型

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

我想实现这样的目标:

template<class... Args>
class MyClass{
public:
MyClass(){
for(auto arg : {sizeof(Args)...})
std::cout<<arg<<std::endl;
}
};

但有一个简单的异常(exception)。 char* 类型应返回 0(或其他所有与 int 不同的值)。

最佳答案

下面的怎么样?

/* heavily borrowed from IBM's variadic template page */
#include <iostream>
using namespace std;

/*
template<typename T> struct type_size{
operator int(){return sizeof( T );}
};

template<> struct type_size <char *>{
operator int(){return 0;}
};
*/
/* as per Mattieu M.'s suggestion */
template<typename T> constexpr size_t type_size(T dummy) {
return sizeof dummy;
}

constexpr size_t type_size(char *){
return 0;
}
template <typename...I> struct container{
container(){
int array[sizeof...(I)]={type_size<I>()...};
printf("container<");
for(int count = 0; count<sizeof...(I); count++){
if(count>0){
printf(",");
}
printf("%d", array[count]);
}
printf(">\n");
}
};

int main(void){
container<int, short, char *> g;
}

关于c++ - 检查传递给可变参数模板的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10373692/

25 4 0
文章推荐: html - 我的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com