問題描述
我對模板的理解類模板的參數推導 提議是在推導上下文中將模板函數和模板類的行為同質化.但我覺得我誤解了一些東西.
My understanding about the Template argument deduction for class templates proposal was to homogenize the behaviour of template functions and template classes in deduction contexts. But I think that I have misunderstood something.
如果我們有這個模板對象:
If we have this template object:
template <std::size_t S, typename T>
struct test
{
static constexpr auto size = S;
using type_t = T;
test(type_t (&input)[size]) : data(input) {}
type_t (&data)[size]{};
};
我傾向于使用輔助函數作為語法糖來創(chuàng)建test
對象:
I tend to use a helper function as syntactic sugar for creating test
objects:
template <std::size_t S, typename T>
test<S, T> helper(T (&input)[S]) { return input; }
如下圖所示:
int main()
{
int buffer[5];
auto a = helper<5, int>(buffer); // No deduction
auto b = helper<5>(buffer); // Type deduced
auto c = helper(buffer); // Type and size deduced
std::cout << a.size << b.size << c.size;
return 0;
}
上面的代碼按預期輸出 555
.我使用較新的編譯器設置在 Wandbox 中嘗試了相同的操作1:
The code above outputs 555
as expected. I've tried the same in Wandbox using the newer compiler setup1:
int main()
{
int buffer[5];
test<5, int> a(buffer); // No deduction: Ok.
test<5> b(buffer); // Type deduced: FAILS.
test c(buffer); // Type and size deduced: Ok.
std::cout << a.size << b.size << c.size;
return 0;
}
看起來類模板的模板參數推導僅適用于推導所有參數,我期望兩種行為(輔助函數和類模板)是相同的,我是否誤解了什么?
It looks like template argument deduction for class templates works only deducing all the parameters, I was expecting both behaviours (helper function and class template) to be the same, did I misunderstood something?
1Wandbox 中最后可用的編譯器是 gcc HEAD 7.0.1 201701 和 clang HEAD 5.0.0 (trunk).>
1The last compilers availables in Wandbox are gcc HEAD 7.0.1 201701 and clang HEAD 5.0.0 (trunk).
推薦答案
來自這個優(yōu)秀的旅行報告 由 Botond Ballo 撰寫:
From this excellent trip report by Botond Ballo:
最初提議的功能包括部分推導的規(guī)定,您可以在其中明確指定一些模板參數,并將其余部分推導,但由于擔心在某些情況下可能會非?;靵y,因此將其撤消:
The feature as originally proposed included a provision for partial deduction, where you explicitly specify some of the template arguments, and leave the rest to be deduced, but this was pulled over concerns that it can be very confusing in some cases:
// Would have deduced tuple<int, string, float>,
// but tuple<int> is a well-formed type in and of itself!
tuple<int> t(42, "waldo", 2.0f);
這篇關于C++17類模板部分推導的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!