模板类型参数未按需要扩展
Template type paremeter not expanding as desired
我在 c++
TMP 上进行试验时注意到模板的强大功能。
但在某些时候我想知道为什么下面的代码无效但它使用可变模板类型扩展(1)。当非类型可变参数扩展工作正常时 (2)。偏差没有意义,因为两个扩展参数都将不可用。还是我的编译器有问题。 clang++ std=c++20
测试
template<typename Y> struct Exp{
static const bool useless=false;
};
template<typename... T> auto initAll1(int forAll,T...ts){
std::array a={(ts,forAll)...};
}
template<typename... T> auto initAll2(int forAll){
std::array a={(T,forAll)...};
}
template<typename... T> auto initAll3(int forAll){
std::array a={(Exp<T>::useless,forAll)...};
return a;
}
我说的是initAll2
。它不起作用,我做了 initAll3
以避免错误。
正如 max66 的评论所说,选项 3 可能不会有任何运行时开销。但是如果你想要更干净的东西,你可以这样做:
template<typename... T>
auto initAll2(int forAll){
std::array a={std::conditional_t<true, int, T>{ forAll }...};
}
我在 c++
TMP 上进行试验时注意到模板的强大功能。
但在某些时候我想知道为什么下面的代码无效但它使用可变模板类型扩展(1)。当非类型可变参数扩展工作正常时 (2)。偏差没有意义,因为两个扩展参数都将不可用。还是我的编译器有问题。 clang++ std=c++20
template<typename Y> struct Exp{
static const bool useless=false;
};
template<typename... T> auto initAll1(int forAll,T...ts){
std::array a={(ts,forAll)...};
}
template<typename... T> auto initAll2(int forAll){
std::array a={(T,forAll)...};
}
template<typename... T> auto initAll3(int forAll){
std::array a={(Exp<T>::useless,forAll)...};
return a;
}
我说的是initAll2
。它不起作用,我做了 initAll3
以避免错误。
正如 max66 的评论所说,选项 3 可能不会有任何运行时开销。但是如果你想要更干净的东西,你可以这样做:
template<typename... T>
auto initAll2(int forAll){
std::array a={std::conditional_t<true, int, T>{ forAll }...};
}