gpt4 book ai didi

c++ - 仅接受某些类型的C++模板

转载 作者:行者123 更新时间:2023-12-02 10:31:08 24 4
gpt4 key购买 nike

在Java中,您可以定义仅接受扩展您选择的类的类型的通用类,例如:

public class ObservableList<T extends List> {
...
}

这是使用“extends”关键字完成的。

在C++中,是否有与此关键字等同的简单名称?

最佳答案

我建议与Boost类型特征库中的static assert一起使用Boost的 is_base_of 功能:

template<typename T>
class ObservableList {
BOOST_STATIC_ASSERT((is_base_of<List, T>::value)); //Yes, the double parentheses are needed, otherwise the comma will be seen as macro argument separator
...
};

在其他一些更简单的情况下,您可以简单地前向声明全局模板,而仅针对(有效地)定义(明确或部分专门化)它:
template<typename T> class my_template;     // Declare, but don't define

// int is a valid type
template<> class my_template<int> {
...
};

// All pointer types are valid
template<typename T> class my_template<T*> {
...
};

// All other types are invalid, and will cause linker error messages.

[次要编辑,2013年6月12日:使用已声明但 undefined 的模板将导致链接器(而非编译器)错误消息。]

关于c++ - 仅接受某些类型的C++模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62219689/

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