这个小程序
#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>':部分特化的非类型参数必须是简单标识符”。
我想知道,要使此代码在 VS 2013 中运行,需要进行的最小/最佳更改是什么。
编辑尝试以不同的方式重新表述:我如何获得元组大小作为编译时常量,可以用作模板参数?
编辑 基本上,使用 integral_costant<int, ID>
而不是int ID
解决了问题。
最佳答案
我被要求创建一个答案。您需要将数字包装在类型中
template<typename ID, class MSGT>
struct addVarDescImpl;
template<int ID, class MSGT>
struct addVarDesc : addVarDescImpl<std::integral_constant<int, ID>, MSGT>
{};
template<typename ID, class MSGT>
struct addVarDescImpl
{
static void exec(MetaData& md, string varNames)
{
typedef typename std::tuple_element<ID::value, typename MSGT::values_type>::type varType;
md.addVar<ID::value, varType>(varNames);
addVarDesc<ID::value+1, MSGT>::exec(md, varNames);
}
};
template<class MSGT>
struct addVarDescImpl<
std::integral_constant<int, std::tuple_size<typename MSGT::values_type>::value>,
MSGT>
{
static void exec(MetaData& md, string varNames)
{
}
};
关于c++ - std::tuple_size 和部分专用模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22115837/