c++ - 我们如何使用模板参数类型的变量?

标签 c++ templates

在下面的代码中,我将类类型 R 和该类型的常量表达式作为模板参数传递。但 clang 不接受这一点:

#include <iostream>

template<class T, T t>
void foo(){ std::cout << "foo()" << std::endl; }

class R
{
public:
    int f;
    constexpr R(): f(15){ }
};

constexpr R r;

int main(){ foo<R, r>(); } //note: candidate template ignored: 
                           //invalid explicitly-specified argument 
                           //for template parameter 't'

<强> DEMO

N4296::14.3.2 [temp.arg.nontype]中,除了非类型模板参数应该是常量表达式之外,我找不到任何限制。

最佳答案

§14.1 [温度参数]/p4:

A non-type template-parameter shall have one of the following (optionally cv-qualified) types:

  • integral or enumeration type,
  • pointer to object or pointer to function,
  • lvalue reference to object or lvalue reference to function,
  • pointer to member,
  • std::nullptr_t.

类类型不是这些。

关于c++ - 我们如何使用模板参数类型的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28379727/

相关文章:

c++ - 如何在不根据相机移动移动或调整大小的情况下将 GUI 保持在屏幕上

c++ - 编译器不能自己判断一个变量是否为 const 吗?

java - 寻找一种在速度模板中检索日期的方法

c++ - 将迭代器传递给函数

c++模板类 - 方法中的类变量不可用

javascript - 如何使用 nbind 包装由 FlatBuffers 编译器生成的 C++ gRPC 接口(interface)作为 Javascript/Typescript 接口(interface)?

c++ - 在 C++ 中,如何制作将未指定类型括在括号内的输出流?

c++ - 尝试获取物理设备时出现Vulkan错误VK_ERROR_INITIALIZATION_FAILED

c++ - 通过初始化列表中的模板类构造函数调用非模板基类的构造函数

c++:如果条件不满足,函数调用会出现编译时错误?