wye*_*r33 3 c++ templates c++11 c++14
有没有一种好方法可以完美地转发模板化类中的函数?具体来说,在代码中
#include <iostream>
// Forward declare a Bar
struct Bar;
// Two different functions that vary based on the kind of argument
void printme(Bar const & bar) {
std::cout << "printme: constant reference bar" << std::endl;
}
void printme(Bar && bar) {
std::cout << "printme: r-value reference bar" << std::endl;
}
void printme2(Bar const & bar) {
std::cout << "printme2: constant reference bar" << std::endl;
}
void printme2(Bar && bar) {
std::cout << "printme2: r-value reference bar" << std::endl;
}
// Some class with a bunch of functions and possible some data (though, not
// in this one)
template <typename T>
struct Foo {
void baz(T && t) {
printme(std::forward <T> (t));
}
void buz(T && t) {
printme2(std::forward <T> (t));
}
};
struct Bar {};
int main() {
Foo <Bar> foo;
foo.baz(Bar());
// Causes an error
Bar bar;
//foo.buz(bar);
}
Run Code Online (Sandbox Code Playgroud)
取消注释最后一点代码,我们得到错误:
test03.cpp: In function 'int main()':
test03.cpp:51:16: error: cannot bind 'Bar' lvalue to 'Bar&&'
foo.buz(bar);
^
test03.cpp:30:10: note: initializing argument 1 of 'void Foo<T>::buz(T&&) [with T = Bar]'
void buz(T && t) {
^
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1
Run Code Online (Sandbox Code Playgroud)
现在,我们可以通过在类中移动模板参数来解决这个问题:
test03.cpp: In function 'int main()':
test03.cpp:51:16: error: cannot bind 'Bar' lvalue to 'Bar&&'
foo.buz(bar);
^
test03.cpp:30:10: note: initializing argument 1 of 'void Foo<T>::buz(T&&) [with T = Bar]'
void buz(T && t) {
^
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1
Run Code Online (Sandbox Code Playgroud)
但是,这似乎非常冗长。例如,假设我们有大量的函数,它们都依赖于类型T并且需要完美转发。我们需要为每个单独的模板声明。此外,该类Foo可能包含一个类型的数据,T我们需要与该数据一致的函数。当然,类型检查器会发现不匹配,但是这个系统并不像只有一个模板参数那么简单,T.
基本上,我想知道的是是否有更好的方法来做到这一点,还是我们只是分别对类中的每个函数进行模板化?
模板非常不同。
在第一个代码中,您的模板参数是Bar,所以我什至不确定它在做什么,因为您不应该使用std::forwardexcept 与引用限定类型。我认为这是void buz(Bar&& t) {printme((Bar)t);}和编译器在通过左值犹豫不决bar中main于预期的功能Bar&&。
在第二个码块,模板参数是Bar&由于通用参考,因此代码void buz(Bar& t) {printme((Bar&)t);},其结合到左值bar在main就好了。
如果你想要完美的转发,模板参数必须是你想要传递的右值限定类型,这意味着你几乎总是必须让函数本身被模板化。但是,帮自己一个忙,给它起个不同的名字。TheT和 theT_将是不同的类型。
template <typename U>
void buz(U&& t) {
printme2(std::forward<U>(t));
}
Run Code Online (Sandbox Code Playgroud)
如果你想要 SFINAE,你也可以添加:
template <typename U,
typename allowed=typename std::enable_if<std::is_constructible<Bar,U>::value,void*>::type
>
void buz(U && t) {
printme2(std::forward <U> (t));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1196 次 |
| 最近记录: |