C++ 无法使用常量字符*数组实例化模板
下面的代码需要帮助,非常困惑什么是错误的C++ 无法使用常量字符*数组实例化模板,c++,visual-studio,c++11,visual-c++,c++14,C++,Visual Studio,C++11,Visual C++,C++14,下面的代码需要帮助,非常困惑什么是错误的 template<const char* (&ArrayC)[]> class TypeDescriptionBase { public: static const auto getType(int index) { return getArrayIndex(ArrayC, index);
template<const char* (&ArrayC)[]>
class TypeDescriptionBase
{
public:
static const auto getType(int index)
{
return getArrayIndex(ArrayC, index);
}
template <typename Func>
static void forEachType(Func&& f)
{
for (const auto& type : ArrayC)
f(type);
}
static auto findTypeIndex(const CString& strType)
{
auto it = std::find(std::begin(ArrayC), std::end(ArrayC), strType);
return static_cast<int>(it == std::end(ArrayC) ? 0 : std::distance(std::begin(ArrayC), it));
}
};
using advancedTypes = TypeDescriptionBase<{ "TypeA", "TpyeB" , "TpyeC", "TpyeD", "TpyeE", "TpyeF", "TpyeG", "TpyeH", "TpyeI", "TpyeJ"}>;
模板
类TypeDescriptionBase
{
公众:
静态常量自动获取类型(int索引)
{
返回getArrayIndex(ArrayC,index);
}
模板
静态void forEachType(Func&f)
{
用于(常数自动&类型:ArrayC)
f型;
}
静态自动查找类型索引(常量CString和strType)
{
autoit=std::find(std::begin(ArrayC)、std::end(ArrayC)、strType);
返回静态_cast(it==std::end(ArrayC)?0:std::distance(std::begin(ArrayC),it));
}
};
使用advancedTypes=TypeDescriptionBase;
我得到了一个错误——“需要一个表达式”,最后一行是常量char*数组的开头。我正在使用VS2017进行开发。您正在尝试使用字符串数组作为模板参数。这在C++中是不被支持的。即使是一个字符串也不能是C++中的模板参数。单个字符可以,因为它们是整数类型。您正在尝试使用字符串数组作为模板参数。这在C++中是不被支持的。即使是一个字符串也不能是C++中的模板参数。单个字符可以,因为它们是整数类型。必须在模板中使用整数类型。其中,您有引用,因此可以使用引用作为模板类型
template<std::vector<std::string> & temp>
class TypeDescriptionBase
{
public:
static void ListTypes()
{
for (auto const & it: temp)
{
std::cout<<it<<std::endl;
}
}
};
int main()
{
std::vector<std::string> vect;//must not be local as it must have external linkage!
vect.emplace_back("Type1");
vect.emplace_back("Type2");
vect.emplace_back("Type3");
vect.emplace_back("Type4");
TypeDescriptionBase<vect> types;
types.ListTypes();
return 0;
}
您必须在模板中使用整型。其中,您有引用,因此可以使用引用作为模板类型
template<std::vector<std::string> & temp>
class TypeDescriptionBase
{
public:
static void ListTypes()
{
for (auto const & it: temp)
{
std::cout<<it<<std::endl;
}
}
};
int main()
{
std::vector<std::string> vect;//must not be local as it must have external linkage!
vect.emplace_back("Type1");
vect.emplace_back("Type2");
vect.emplace_back("Type3");
vect.emplace_back("Type4");
TypeDescriptionBase<vect> types;
types.ListTypes();
return 0;
}
你想做的不是C++。沿着这条路线走下去是在阿尔伯克基。你想做的不是C++。沿着这条路线走的是阿尔伯克基。