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

How can we use a variable of the type of the template parameter?

在下面的代码中,我将 class 类型 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 [temp.param]/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.

一个class类型是none个。