假设我有一个完善的转发功能:
template <typename T>
void f(T&& t) { /* does something */ }
我有特定类型
T
,我想允许复制列表初始化,比如 std::pair<int, int>
:
f({1, 2}); // I want to do this
我知道为此我必须超载
f(const std::pair<int, int>&)
。如何在 f(T&&)
内调用 f(const std::pair<int, int>&)
?
void f(const std::pair<int, int>& p) {
f(p); // How do I make this resolve to f(T&&)?
}
您可以添加间接级别:
#include <utility>
#include <iostream>
template <typename T>
void f_impl(T&& t) {
std::cout << "call\n";
}
template <typename T>
void f(T&& t) {
f_impl(std::forward<T>(t));
}
void f(const std::pair<int,int>& p) {
f_impl(p);
}
int main() {
f({1, 2}); // I want to do this
}