Дефаултное значение произвольного типа
Пытаюсь в условный оператор запихать дефаултное значение неизвестного типа. В большинстве случаев срабатывает
return t ? t->f() : decltype (t->f()) {};
Однако, если выведенным типом оказывается void, то получается ошибка компиляции
prog.cpp: In instantiation of ‘auto call(T*) [with T = smth1]’:
prog.cpp:22:11: required from here
prog.cpp:17:12: error: compound literal of non-object type ‘void’
return t ? t->f() : decltype (t->f()) {};
~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Есть ли способ поместить значение прямо в условный оператор, или единственный вариант - оборачивать всё это в if constexpr и дублировать код?
if constexpr (is_void_v<decltype(t->f())>) { if (t) return t->f(); }
else return t ? x->f() : decltype(t->f()){};
Код полностью: https://ideone.com/cAlFlT
struct smth1
{
void f() {}
} a1;
struct smth2
{
int f() { return 88; }
} a2;
template <typename T> auto call(T *t)
{
return t ? t->f() : decltype (t->f()) {};
}
int main()
{
call(&a1);
call(&a2);
return 0;
}
Ответы (1 шт):
Автор решения: user394289
→ Ссылка
struct smth1
{
void f() {}
} a1;
struct smth2
{
int f() { return 88; }
} a2;
template <typename T> auto call(T *t)
{
return t ? t->f() : decltype(t->f())();
}
int main()
{
smth1* v1 = nullptr;
smth2* v2 = nullptr;
call(&a1);
call(&a2);
call(v1);
call(v2);
// ок, void expression
void();
// синтаксическая ошибка, не может быть ни zero initialization, ни compound literal, т.к. void не является complete object type
// void{};
return 0;
}