c++ - 向类模板特化添加方法

标签 c++ templates stl template-specialization

我想实现 STL 中存在的行为:当我们查看 vector 容器时,已知它具有 vector<bool>添加方法的特化 flip()

是否可以实现这样的类扩展,而无需将整个类复制为特化并在其主体中添加新方法?

最佳答案

你可以SFINAE“特化”的方法

template <typename T>
class C
{
public:
    // Common code...

    template <typename U = T, std::enable_if_t<std::is_same<bool, U>::value, bool> = false>
    void only_for_bool() {/*..*/}
};

C++20 将允许更好的语法:

template <typename T>
class C
{
public:
    // Common code...

    void only_for_bool() requires (std::is_same<bool, T>::value) {/*..*/}
};

关于c++ - 向类模板特化添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54851119/

相关文章:

css - Joomla - 模板消失

c++ - 使用 STL vector 管理 opengl 缓冲区对象

c++ - 具有可访问构造函数的 std::vector< T >::iterator

c++ - 删除在另一个对象的构造函数中创建的 "new object"?

c++ - 动态内存分配和指针非字符数组类型

c++ - 构建 wxWidgets 应用程序失败 - 未定义对 `wxCRT_StrdupA(char const*)' 的引用

c++ - 如何将 etrace 与动态库一起使用以按时间顺序跟踪 C++ 中的函数调用?

c++ - 仅使用静态多态性的异构容器

c++ - 在多个文件之间拆分模板特化会导致 ODR 违规吗?

c++ - 与 C 字符串 `std::string` + (`malloc` 相比, `memcpy` 的性能真的很差)