c++ - 可以推断左值引用非类型模板参数吗?

标签 c++ templates c++11 language-lawyer lvalue

我有以下代码,我无法开始工作:

struct foo {};
foo foo1 = {};

template <foo& F>
class FooClass {};

template <foo& F>
void foobar(FooClass<F> arg) {
}

int main() {
    FooClass<foo1> f;
    foobar(f);
}

错误是:

main.cpp:14:5: error: no matching function for call to 'foobar'

note: candidate template ignored: substitution failure : deduced non-type template argument does not have the same type as the its corresponding template parameter ('foo' vs 'foo &')

可能推断左值引用模板参数吗?如果可以,应该怎么做?

最佳答案

CWG 2091 恰好涵盖了这一点:

According to 14.8.2.5 [temp.deduct.type] paragraph 17,

If P has a form that contains <i>, and if the type of the corresponding value of A differs from the type of i, deduction fails.

这给出了如下示例的错误结果:

template<int &> struct X;
template<int &N> void f(X<N>&);
int n;
void g(X<n> &x) { f(x); }

在这里,PX<N> ,其中包含 <i> . i 的类型是int& . 对应的值来自An , 这是类型的左值 int .大概这应该是有效的。

我认为这条规则的意思是说,

If P has a form that contains <i>, and the type of i differs from the type of the corresponding template parameter of the template named by the enclosing simple-template-id, deduction fails.

如@dyp所述,[temp.deduct.type]/17应该更宽容。在您的示例中,FooClass<F> 中的参数( F ) 没有引用类型 - 它是 foo 类型的左值. FooClass的模板参数是一个引用。 DR 已于去年解决。

关于c++ - 可以推断左值引用非类型模板参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35139955/

相关文章:

c++ - 在 C++ 中搜索文件中的字符串以获得非常大的输入的有效方法

c++ - 使用enable_if 的模板类定义会导致错误

c++ - 移除未使用的模板实例化的静态成员

c++ - 如何在编译时交换可变参数模板的两个参数?

c++ - int p 不是 lpNorm<p> 中的常量表达式

c++ - 为什么在使用 operator class_name() & c 样式转换时 g++ 会出现错误

c++ - 代码已退出-1073741515(0xc0000135) 'A dependent dll was not found'

c++ - 成员变量包装器

c++ - 如何使用 GnuGK 或 OpenH323gk 配置 makecall?

c++ - 在映射中存储模板类函数指针