gpt4 book ai didi

c++ - C++11 模板中的默认位置参数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:05:32 25 4
gpt4 key购买 nike

允许将模板参数留空(使用 <>),您如何将位置参数留空或对其进行修改以达到相同的效果。

template <int i = 0, int j = 1, int k = 2>
void blah() {
std::cout << i << " " << j << " " << k << std::endl;
}

int main() {
blah(); // ok
blah<>(); // ok
blah<1>(); // ok, i = 1
blah<1,,3>(); // not ok, i = 1, j = 1 (default), k = 3
return 0;
}

最佳答案

这是不可能的。你必须通过它。

这里有一个建议:

auto constexpr default_j = 1;

template <int i = 0, int j = default_j, int k = 2>
void blah() {
std::cout << i << " " << j << " " << k << std::endl;
}

int main() {
blah(); // ok
blah<>(); // ok
blah<1>(); // ok, i = 0
blah<1, default_j, 3>(); // ok, explicit and without duplicate magic numbers!
return 0;
}

关于c++ - C++11 模板中的默认位置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24881131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com