e.g. I have the following Foo class with the foo() to check if all the types are std::int32_t
class Foo {
public:
/// check if all the types are std::int32_t
template<typename ...Ts>
bool foo() {
return true && std::is_same<Ts, std::int32_t>::value...;
}
};
int main()
{
Foo f;
std::cout<<f.template foo<std::int32_t, std::int32_t>(); //true
std::cout<<f.template foo<std::int32_t, std::int64_t>(); //false
return 0;
}
return true && std::is_same<Ts, std::int32_t>::value...;
is not a correct syntax. How do I make it correct?
CodePudding user response:
https://en.cppreference.com/w/cpp/language/fold
return (true && ... && std::is_same<Ts, std::int32_t>::value);
# or
return (std::is_same<Ts, std::int32_t>::value && ... && true);
# or really just
return (std::is_same<Ts, std::int32_t>::value && ...);
CodePudding user response:
It looks like a variable template(since c 14), is mor appriopriate there.
Using std::conjunction
(since c 17) you can write less verbose.
#include <type_traits> // std::conjunction
struct Foo
{
// check if all the types are std::int32_t
template<typename ...Ts>
inline static constexpr bool areInt32 = std::conjunction_v<std::is_same<Ts, std::int32_t>...>;
};
And you write
std::cout << f.areInt32<std::int32_t, std::int32_t>;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^