当我发现模板的功能强大时,我在c++
TMP上进行了试验。
但是在某些时候,我想知道以下代码为何无效,但它使用可变参数模板类型expandment(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++ - 模板类型参数未按要求扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64953932/