【发布时间】:2014-03-01 14:51:49
【问题描述】:
这个小程序
#include <iostream>
#include <tuple>
#include <string>
using namespace std;
class MetaData
{
public:
template<int ID, class T>
void addVar(string varNames)
{
// do smth
}
template<int ID, class MSGT>
struct addVarDesc
{
static void exec(MetaData& md, string varNames)
{
typedef typename std::tuple_element<ID, typename MSGT::values_type>::type varType;
md.addVar<ID, varType>(varNames);
addVarDesc<ID+1, MSGT>::exec(md, varNames);
}
};
template<class MSGT>
struct addVarDesc<std::tuple_size<typename MSGT::values_type>::value, MSGT>
{
static void exec(MetaData& md, string varNames)
{
}
};
template<class MSGT>
static MetaData createMetaData(string varNames)
{
MetaData md;
MetaData::addVarDesc<0, MSGT>::exec(md, varNames);
return md;
}
};
template<typename... Types>
class Message
{
public:
tuple<Types...> m_values;
typedef tuple<Types...> values_type;
static MetaData m_meta;
};
typedef Message<string, double> MyMessageType;
template<>
MetaData MyMessageType::m_meta = MetaData::createMetaData<MyMessageType>("name\nmass");
int main() {
// your code goes here
return 0;
}
在 gcc 中编译良好,但在 MS Visual Studio 2013 中会产生“错误 C2755: 'MetaData::addVarDesc::value,MSGT>' : non-type parameter of a partial specialization must be a simple identifier”。
我想知道,此代码在 VS 2013 中工作所需的最小/最佳更改是什么。
编辑尝试换一种说法:如何将元组大小作为编译时常量,有资格用作模板参数?
编辑基本上,使用integral_costant<int, ID> 而不是int ID 解决了这个问题。
【问题讨论】:
-
此代码格式不正确,请参阅 open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1315 。您需要将
ID设置为类型参数,并将std::tuple_size<...>::value包装在int_<...>或std::integral_constant<int, ...>中。见stackoverflow.com/questions/5978617/… -
好吧,gcc 不介意,考虑到它在标准合规性方面通常比微软的要好,我认为可能没有标准限制。你能写一个答案,以便我可以将问题标记为已解决吗?
标签: c++ templates visual-c++ c++11 variadic-templates