这个编译时间图有什么问题?

时间:2017-09-15 04:31:18

标签: c++11 templates template-meta-programming

我很难理解为什么我不能输入这个地图,编译器抱怨

main.cpp:14:41: error: type/value mismatch at argument 1 in template 
parameter list for 'template<class ...> struct Map'
struct Map<KeyType, Key, Value, Rest...> {
                                     ^
main.cpp:14:41: note:   expected a type, got 'Key'
main.cpp:24:23: error: type/value mismatch at argument 1 in template 
parameter list for 'template<class ...> struct Map'
typedef Map<int, 1, A> map;

这是代码

#include <type_traits>
#include <iostream>

 template<typename...>
 struct Map;

 template<typename KeyType>
 struct Map<KeyType> {
   template<KeyType NotFound>
   struct get { typedef std::false_type val; };
 };

 template<typename KeyType, KeyType Key, typename Value, typename... Rest>
 struct Map<KeyType, Key, Value, Rest...> {
     template<KeyType Get>
     struct get {
         typedef std::conditional<Get == Key, Value, typename Map<KeyType, Rest...>::template get<Get>::val> val;
     };
 };

 struct A { static constexpr int value = 1; };
 struct B { static constexpr int value = 2; };

 typedef Map<int, 1, A> map;

 int main() {
   std::cout << map::get<1>::val::value << std::endl;
   //std::cout << map::get<2>::val::value << std::endl;
   //std::cout << map::get<3>::val::value << std::endl;
 }

似乎某种方式将地图typedef中的第一个键作为键类型,我不确定是怎么发生的。

修改

我找到了一个解决方案,目标是从一些常量值到一个类型有一个编译时间映射,所以我可以在编译时将枚举映射到类型。我能够通过将Key包装在一个类型中,并将KeyType作为第一个模板参数传递给地图来解决问题。一些样板类型定义使它不像template<int V> using IntMap = Map<MyKey<int, V>;template<MyEnum E> using MyEnumMap = Map<MyEnum, E>那样难看。我相信使用c ++ 17自动模板可以使这些更清晰。请评论。

    #include <type_traits>
#include <iostream>

template<typename KeyType, KeyType Key>
 struct KeyValue {};

 struct KeyNotFound {};

 template<typename...>
 struct Map;

 template<typename KeyType>
 struct Map<KeyType> {
   template<KeyType Key>
   struct get { typedef KeyNotFound type; };
 };

 template<typename KeyType, KeyType Key, typename Value, typename... Rest>
 struct Map<KeyType, KeyValue<KeyType, Key>, Value, Rest...> {
     template<KeyType Get>
     struct get {
         typedef typename std::conditional<Get == Key, Value, typename Map<KeyType, Rest...>::template get<Get>::type>::type type;
     };
 };

 struct A { static constexpr int value = 1; };
 struct B { static constexpr int value = 2; };


 typedef Map<int,
     KeyValue<int, 1>, A, 
     KeyValue<int, 2>, B> map;

 int main() {
   std::cout << map::get<1>::type::value << std::endl;
   //std::cout << map::get<2>::val::value << std::endl;
   //std::cout << map::get<3>::type::value << std::endl;
 }

1 个答案:

答案 0 :(得分:0)

Map的前向声明只能看到类型参数。您在特化中使用非类型参数,这是不允许的。

编译器抱怨的是什么。

我无法提出解决方案,因为我不知道你想要通过混合类型和非类型参数来完成什么。