C++ std::和std::是一样的吗
我试图检查某个特定类型是否被放入类型列表(元组)。遇到了一些麻烦:C++ std::和std::是一样的吗,c++,tuples,metaprogramming,C++,Tuples,Metaprogramming,我试图检查某个特定类型是否被放入类型列表(元组)。遇到了一些麻烦: #include <tuple> #include <iostream> template < typename T > struct Type { using type = T; }; int main() { constexpr auto Foo = std::make_tuple(Type<int>{},Type<int>{}); if (
#include <tuple>
#include <iostream>
template < typename T >
struct Type {
using type = T;
};
int main() {
constexpr auto Foo = std::make_tuple(Type<int>{},Type<int>{});
if (std::is_same<int, std::get<0>(Foo)::type>::value)
std::cout << "GG!" << std::endl;
return 0;
}
test.cpp: In function ‘int main()’:
test.cpp:13:47: error: type/value mismatch at argument 2 in template parameter list for ‘template<class, class> struct std::is_same’
if (std::is_same<int, std::get<0>(Foo)::type>::value)
^
test.cpp:13:47: note: expected a type, got ‘std::get<0ul, {Type<int>, Type<int>}>(Foo)’
#包括
#包括
模板
结构类型{
使用类型=T;
};
int main(){
constexpr auto Foo=std::make_tuple(类型{},类型{});
if(std::is_same::value)
std::coutstd::get(Foo)::type
在这种上下文中没有任何意义,因为std::get(Foo)
是一个值,而不是一个类型
相反,请尝试以下操作:我们将使用decltype()
获取该表达式的类型(而不实际计算其值)。这将导致类型&
类型。我们将使用删除引用(因为类型&::type
也没有意义),然后我们可以访问其类型
类型定义
这有点笨重,但它可以工作:
if (
std::is_same<
int,
// The decltype will be (Type<int>&). Decay to remove the
// reference, cv-qualifiers, etc.
std::decay<
decltype(std::get<0>(Foo))
>::type::type
// ^ Two ::types, one to extract the type from std::decay, one
// for your Type<T> struct.
>::value
) {
std::cout << "GG!" << std::endl;
}
if(
std::是一样的吗<
int,
//decltype将为(Type&)。要删除
//参考、cv限定符等。
标准::衰变
decltype(std::get(Foo))
>::类型::类型
//^2个::类型,一个从std::decay提取类型,一个
//对于您的类型结构。
>::价值
) {
std::coutget
返回一个值,而不是一个类型。尝试将调用包装成一个decltype
来查找类型。不过,我面前没有编译器来检查atm。是的,我希望我能做得更好,我将检查Boost::Hana。由于这一点:)更短(或者至少更容易摸索)版本应该是std::is_same::value
,但请注意,这取决于Foo
是一个元组。我的答案中的版本还应该与std::pair
和其他一些类型一起使用。对尽可能多的表达式使用decltype
可以使模板更加灵活。这是一个有点复杂的版本重新阅读,很好!不过还是要去看看图书馆。无论如何,谢谢!