請考慮下面的例子(標籤調度,可變參數模板,完善的轉發,等等,都在同一個):標籤調度,可變參數模板,通用參考,並錯過常量符
#include <iostream>
#include <utility>
#include <string>
struct A { };
struct B { };
void doIt(A&&, const std::string &) {
std::cout << "A-spec" << std::endl;
}
template<typename T, typename... Args>
void doIt(T&&, Args&&...) {
std::cout << "template" << std::endl;
}
template<typename T, typename... Args>
void fn(Args&&... args) {
doIt(T{}, std::forward<Args>(args)...);
}
int main() {
const std::string foo = "foo";
std::string bar = "bar";
fn<A>(foo);
fn<A>(bar);
fn<B>(foo);
}
在這種情況下,輸出是:
A-spec
template
template
的原因是很明顯的,它不會打擾我。
我想要實現的是在這兩種情況下調用doIt
函數的第一個實例,而不管該字符串是否具有常量說明符。
當然,一個可能的解決方案是用正確的原型定義一個新的doIt
,無論如何我想知道是否還有其他解決方案。
到目前爲止,我試圖通過add_const
得到它,但我確定我錯過了一些東西。
是否有任何可行的解決方案來靜默添加const說明符並使其工作?
編輯
我已經更新上面的例子中,爲了與真正的問題更加連貫。
此外,儘管有趣的答案,我忘了引用這只是一個簡化的例子,所以真正的問題不只涉及std::string
。相反,對標籤A
的參數(作爲示例)可能發生的參數是int
和const std::string &
,而對於標籤B
,參數是float
,類C
的實例等等。
因此,那些試圖用std::string
類型解決問題的答案不會解決真正的問題,我很抱歉。
我認爲更改後,'doIt'的模板版本仍然應該使用完美的轉發? – Angew
@skypjack是[this](http://coliru.stacked-crooked.com/a/b4beb48345f47162)你需要什麼? –
@PiotrSkotnicki只有當你把所有的東西放在一個更詳細的答案中,因爲我仍然試圖找出它爲什麼起作用! :-) ......無論如何,這似乎是我在尋找的確如此。 – skypjack