gpt4 book ai didi

c++ - 如何修复此模板 :

转载 作者:搜寻专家 更新时间:2023-10-31 00:59:22 24 4
gpt4 key购买 nike

template <typename IN,typename OUT,bool isVector>
OUT foo(IN x){
if (isVector){
return x[0];
} else {
return x;
}
}

询问后this question我错误地认为,上面的代码可以编译为例如

foo<double,double,false>;

还有

foo<std::vector<double>,double,true>;

然而,即使其中一个 if 分支从未被执行,它也会被检查其正确性,因此上面的代码不会编译。我该如何解决?

上面的代码是简化的,但我不知道如何修复它,因为函数模板不能有部分特化...

最佳答案

你可以把你想专攻的模板参数“抽取出来”,让它们成为某个结构体的模板参数,把剩下的模板参数写成静态成员函数的函数:

template<bool IsVector = true>
struct Bar {
template<typename In>
static auto foo(In input) {
return input[0];
}
};
template<>
struct Bar<false> {
template<typename In>
static auto foo(In input) {
return input;
}
};

Live example.

显然,这会导致调用站点发生变化,您可以使用调用适当函数的自由函数“捕获”该变化:

template<typename In, bool IsVector>
auto real_foo(In input) {
return Bar<IsVector>::foo(input);
}

然后结构(Bar)通常被放入一个“helper”命名空间。


另一种可能性是使用标签和重载解析:

template<typename In>
auto foo(In input, std::true_type) {
return input[0];
}
template<typename In>
auto foo(In input, std::false_type) {
return input;
}
template<bool IsVector, typename In>
auto foo(In input) {
using tag = typename conditional<IsVector, true_type, false_type>::type;
return foo(input, tag{});
}

Live example.

这使用 std::conditionalstd::true_typestd::false_type 作为不同的类型,以允许重载解析以找到合适的 foo 函数。

关于c++ - 如何修复此模板 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33465830/

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