【问题标题】:how to make this template typedef valid in c++11?如何使此模板 typedef 在 c++11 中有效?
【发布时间】:2018-01-12 07:16:54
【问题描述】:

我有一个这样的代码片段

  map<string, map<string, map<string, float> > >  map_f;
  map<string, map<string, map<string, string> > > map_s;
  map<string, map<string, map<string, double> > > map_d;

我只想把这段代码简明扼要地写成这样:

myMap<float>   map_f;
myMap<string>  map_s;
myMap<double>  map_d;

所以我尝试使用templateusing 来实现:

template<type T>
    using myMap = map<string, map<string, map<string, T> > >;

但是,我得到一个错误:

error: expected expression
template<type T>

我的问题是,如何修改这段代码,这个错误是什么意思?

代码已显示:

#include <string>
#include <map>
using namespace std;

int main()
{
  template<typename T>  
    using myMap = map<string, map<string, map<string, T> > >;
  return 0;
} 

我用c++ 4.2.1 @ mac osX 10.13.2编译它:

g++ -std=c++11 temp_def_cls.cxx -o main

我得到了错误:

temp_def_cls.cxx:7:3: error: expected expression
  template<typename T> 
  ^
1 error generated.

【问题讨论】:

  • 不应该是template&lt;typename T&gt; using myMap = ...吗?
  • @songyuanyao 还是不行,在你的电脑上可以吗?
  • @springcc Yes.
  • 你不能在函数内部做。将其移出函数。
  • @songyuanyao 是的,解决了!

标签: c++ c++11 templates using


【解决方案1】:
template<typename T>
    using myMap = map<string, map<string, map<string, T> > >;

type 在 C++ 中没有什么特别之处。你需要keyword typename(或class这里)。

将该指令移出main()。我使用的是 GCC 7.2.0,消息更清晰:

t.cpp: In function ‘int main()’:
t.cpp:7:3: error: a template declaration cannot appear at block scope
   template<typename T>
   ^

【讨论】:

  • 您好,我尝试了您的代码,但错误仍然相同。我用g++ -std=c++11 temp_def_cls.cxx -o mainc++ 4.2.1 mac os 10.13上编译它
  • 您好,问题已添加完整的代码片段,请查看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 2012-08-04
  • 1970-01-01
  • 2016-08-23
相关资源
最近更新 更多