英文:
Change type of reference based on template parameter
问题
现在我大致有这段代码。
```cpp
Type1 myVarWithAVeryLongName1 = new Type1(); // 实际上是一个指针链,但这样可以明白意思
Type2 myVarWithAVeryLongName2 = new Type2();
template<bool usesType2>
void func() {
//auto& myVar = usesType2 ? myVarWithAVeryLongName2 : myVarWithAVeryLongName1; // 三元表达式不能返回不同类型
/*if constexpr (usesType2) {
auto& myVar = myVarWithAVeryLongName2;
} else {
auto& myVar = myVarWithAVeryLongName1;
} // 将`myVar`放到了作用域外
*/
auto& myVar = ?;
// …
}
英文:
Right now I have roughly this code.
Type1 myVarWithAVeryLongName1 = new Type1(); // Really a chain of pointers, but this gets the point across
Type2 myVarWithAVeryLongName2 = new Type2();
template<bool usesType2>
void func() {
//auto& myVar = usesType2 ? myVarWithAVeryLongName2 : myVarWithAVeryLongName1; // A ternart expression can't return different types
/*if constexpr (usesType2) {
auto& myVar = myVarWithAVeryLongName2;
} else {
auto& myVar = myVarWithAVeryLongName1;
} // Puts `myVar` out of scope
*/
auto& myVar = ?;
// …
}
I want to do a very similar operation on both myVarWithAVeryLongName1
and myVarWithAVeryLongName2
. Since the operation takes lots of code and Type1
and Type2
are so similar, I can save ~300 lines of code by making one function and resolving the few differences with if constexpr
blocks. However, the two variables are a lot to type out, so I alias them with auto& myVar = myVarWithAVeryLongName1;
and use myVar
for the rest of the function. Is there any way to do this?
答案1
得分: 2
以下是您要翻译的内容:
#include <type_traits>
using Type1 = int;
using Type2 = double;
Type1* myVarWithAVeryLongName1 = new Type1();
Type2* myVarWithAVeryLongName2 = new Type2();
template<bool usesType2>
void func() {
using type = std::conditional_t<usesType2, Type2, Type1>;
auto& myVar =
[]() -> type& {
if constexpr(usesType2) {
return *myVarWithAVeryLongName2;
} else {
return *myVarWithAVeryLongName1;
}
}();
// …
}
int main() {
func<true>();
func<false>();
}
希望这有所帮助。
英文:
You can use an immediately invoked lambda and std::conditional_t
:
#include <type_traits>
using Type1 = int;
using Type2 = double;
Type1* myVarWithAVeryLongName1 = new Type1();
Type2* myVarWithAVeryLongName2 = new Type2();
template<bool usesType2>
void func() {
using type = std::conditional_t<usesType2, Type2, Type1>;
auto& myVar =
[]() -> type& {
if constexpr(usesType2) {
return *myVarWithAVeryLongName2;
} else {
return *myVarWithAVeryLongName1;
}
}();
// …
}
int main() {
func<true>();
func<false>();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论