C++ 如何允许复制列表初始化以实现完美的转发功能?

问题描述 投票:0回答:1

假设我有一个完善的转发功能:

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&&)?
}
c++ overload-resolution perfect-forwarding
1个回答
0
投票

您可以添加间接级别:

#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
}
© www.soinside.com 2019 - 2024. All rights reserved.