gpt4 book ai didi

c++ - 为什么我不能手动提供模板参数?

转载 作者:太空狗 更新时间:2023-10-29 21:05:04 26 4
gpt4 key购买 nike

我有一个可变模板函数 f。这可以很好地编译(使用 g++ -std=c++11 并可能使用 c++0x):

#include <tuple>

template<int ...>
struct seq { };

template <typename ...T, int ...S>
void f(std::tuple<T...> arg, seq<S...> s) {
// ... do stuff
}

int main() {
f<int>(std::tuple<int>(10), seq<0>());
return 0;
}

编译器自动填充有效的int ...S

但是,我似乎无法手动提供整数参数:

int main() {
f<int, 0>(std::tuple<int>(10), seq<0>());
return 0;
}

输出:

/tmp/t.cpp: In function ‘int main()’: /tmp/t.cpp:12:42: error: no
matching function for call to ‘f(std::tuple, seq<0>)’
/tmp/t.cpp:12:42: note: candidate is: /tmp/t.cpp:7:6: note:
template void f(std::tuple<_TElements ...>,
seq) /tmp/t.cpp:7:6: note: template argument
deduction/substitution failed:

我相信我已经读到,从技术上讲,应该只向模板函数提供一个可变参数模板参数包(在第一种情况下,它完全由上下文决定),所以这解释了它(?)。

对于调试,GCC 是否有办法将用于 ...S 的扩展输出到 stderrstdout?当它们一开始不编译时,这对于调试这样的东西非常有用。

最佳答案

我不知道如何手动指定两个模板参数包。由于模板包可能包含任意多个参数,因此编译器无法知道您的意思是第一个停止,第二个开始。自动或部分自动扣除似乎有效,但我不确定这是否只是 g++ 的一些慷慨......

我不确定您实际要做什么,但我敢打赌您不会同时需要两个模板包。您可能会引入一层间接寻址,例如,

template <typename ... Tuple_Elements>
void do_something_with_single_value(std::tuple<Tuple_Elements...> arg, int s) {
// ... do stuff
}

template <typename Tuple_Type, int ...S>
void f(Tuple_Type arg, seq<S...> s) {
// ... do stuff which needs all S at the same time
// ... call do_something_with_single_value in compile time loop to access tuple elements
}

也许您的签名暗示您的功能职责太多。尝试创建职责明确的较小功能。

有一种方法可以输出为 T 和 S 推导的参数,但前提是编译器可以确定匹配。为此,您需要在编译时引发错误:

template <typename ...T, int ...S>
void f(std::tuple<T...> arg, seq<S...> s) {
static_assert(std::tuple_size<std::tuple<T...>>::value < 0, "Provoked error message");
// ... do stuff
}

这将在您的工作示例中生成以下输出:

stack.cpp: In function ‘void f(std::tuple<_Elements ...>, seq<S ...>) [with T = {int}, int ...S = {0}]’:
stack.cpp:15:34: instantiated from here
stack.cpp:10:2: error: static assertion failed: "Provoked error message"

关于c++ - 为什么我不能手动提供模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10824811/

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