简体   繁体   English

可变参数模板功能和参考类型

[英]Variadic template function and reference types

As part of a DSL for an OpenCL binding I have to count the arguments given to a function f and handle them seperately, in the code below this would be h . 作为用于OpenCL绑定的DSL的一部分,我必须计算提供给函数f的参数,并分别处理它们,在下面的代码中将是h The function should accept LValues as well as RValues for most types. 对于大多数类型,该函数应接受LValues和RValues。 However, for some types (here: int ) only LValue references are acceptable (in the real code these are objects that might need to initialised lazily). 但是,对于某些类型(此处为int ),仅LValue引用是可接受的(在实际代码中,这些是可能需要延迟初始化的对象)。

My problem: how do I get rid of that const_cast ? 我的问题:如何摆脱该const_cast f(T...) doesn't work, neither does f(T&...) or f(T&&...) f(T...)不起作用, f(T&...)f(T&&...)也不起作用

template<typename T>
void h(int i, const T &x) {/* generic things */}

void h(int i, const int &x) { const_cast<int&>(x) = 123; }

template<int i> void g() {}

template<int i, typename H, typename... T>
void g(H &x, T... xs) {
    h(i, x);
    g<i + 1>(xs...);
}

template<typename... T>
void f(const T&... xs) { g<0u>(xs...); }

#include <cassert>
int main(int, char**) {
    int x = 1;
    f(x, 2.0 + 3.0, 'c');
    assert(x == 123);
}

While writing the question I found a solution, but I don't understand why the signature is int && instead of int & (doesn't seem to matter though?) 在写问题时,我找到了一个解决方案,但是我不明白为什么签名是int &&而不是int & (虽然似乎没有关系?)

template<typename T>
void h(int i, T x) {cerr << i << "=" << x << endl;}

void h(int i, int &&x) {
    x = 123;
    cerr << i << "=" << x << " (new)" << endl;
}

template<int i> void g() {}

template<int i, typename H, typename... T>
void g(H &&x, T &&... xs) {
    h(i, std::move(x));
    g<i + 1>(xs...);
}

template<typename... T>
void f(T &&... xs) { g<0u>(xs...); }

Also, with h(int, T&) the overload h(int, int&&) is called for all three arguments, int , double and char , which looks very suspicious to me (or is this because int x = 2.0, y = 'a'; works, too?) 另外,对于h(int, T&) h(int, int&&)对所有三个参数intdoublechar都调用了重载h(int, int&&) ,这对我来说似乎非常可疑(或者因为int x = 2.0, y = 'a';也行吗?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM