c++ - 非类型模板参数

标签 c++ templates non-type

考虑一下:

#include <set>

template <typename T, T val>
class sample {
public:
    // Return val for new elements.
    T& at(unsigned i) {
       auto o = _set.insert(val);
       return *o.first;
    }

private:
    std::set<T> _set;
};

class s {
public:
    constexpr s() = default;
};


int main() {
    constexpr s val;
    sample<s, val> o2;
    return 0;
}

gcc -std=c++11 无法编译。

non-type.cc: In function ‘int main()’:
non-type.cc:24:18: error: ‘class s’ is not a valid type for a template non-type parameter
     sample<s, val> o2;

正如评论中提到的,我希望“set”的新元素初始化为“val”。由于 val 是恒定的,因此看起来是合理的期望!

有人可以告诉我如何实现它吗?

最佳答案

看起来你想做的事情是可能的,但需要 C++20。

来自docs

在 C++20 之前,“非类型参数”必须是以下之一

- std::nullptr_t (since C++11);
- an integral type;
- a pointer type (to object or to function);
- a pointer to member type (to member object or to member function);
- an enumeration type.

拥有自定义类型的非类型参数目前似乎不可用,除非您可以访问已经具有该功能的编译器。

关于c++ - 非类型模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59527629/

相关文章:

c++ - 我如何使用比率而不是 float ?

c++ - 在类内声明模板化函数(通过容器类型)并在模板类之外通过容器类型定义它 -

c++ - 将 dynamic_cast 与模板一起使用

c++ - 指向模板类全局实例的指针作为模板参数?

c++ - 实例化对象和对象成员

c++ - 方法在类中的位置

c++ - 映射、迭代器和复杂结构 - STL 错误

c++ - 根据构造函数参数推导模板类型

c++ - 编译器编译一个 'io_service_' 变量显示为 : cannot appear in a constant-expression