This is just a code written for testing. I just want to print the lvalue and const information of the given tuple. It works without any errors except the print function. Since the code is short and very understandable, I think there is no need for additional explanation.
Can you help me understand why the code is not working and what I should do to fix it?
#include <iostream>
#include <tuple>
#include <type_traits>
template<typename... Parameters>
struct Test {
Test(Parameters&&... params): parameters_{std::forward<Parameters>(params)...} {}
std::tuple<Parameters...> parameters_;
void print() {
if ( std::is_lvalue_reference<decltype(std::get<0>)(parameters_)>::value ) {
std::cout << "lvalue refn";
} else {
std::cout << "rvalue refn";
}
if ( std::is_const<std::remove_reference_t<decltype(std::get<0>)(parameters_)>>::value ) {
std::cout << "constn";
} else {
std::cout << "non constn";
}
}
};
int main() {
Test<int, float> t{1, 2.2};
t.print();
return 0;
}
Your code doesn’t compile because when you use is_lvalue_reference
and is_const
, the parenthesis are not correctly located.
Here is a working code. Note that one can use using
in order to make the code more readable. Since you didn’t precise a c++ standard, I assume that you could also use _v
extensions for type traits, which makes also the code clearer.
#include <iostream>
#include <tuple>
#include <type_traits>
template<typename... Parameters>
struct Test {
Test(Parameters&&... params): parameters_{std::forward<Parameters>(params)...} {}
std::tuple<Parameters...> parameters_;
void print() {
using type = decltype(std::get<0>(parameters_));
if ( std::is_lvalue_reference_v<type>) {
std::cout << "lvalue refn";
} else {
std::cout << "rvalue refn";
}
if ( std::is_const_v<std::remove_reference_t<type>>) {
std::cout << "constn";
} else {
std::cout << "non constn";
}
}
};
int main() {
Test<int, float> t{1, 2.2};
t.print();
return 0;
}
Demo