【发布时间】:2023-03-24 04:39:01
【问题描述】:
我在非模板类中有一个模板函数,如下所示:
class Foo
{
public:
template <class T>
void func(T& val)
{
//do work here
}
}
然后,我在 main.cpp 中做:
Foo a;
std::string val;
a.func<std::string>(val); //this line gives the error
我收到一条错误消息,提示 “主表达式应在 '>' 之前”。于是我用谷歌快速搜索了一下,发现大家都提出了一个简单的解决方案:
a.template func<std::string>(val);
唯一的问题是,我仍然遇到完全相同的错误。
编辑:
我没有给出完整示例的原因是因为它涉及到外部库和冗长的代码,这会掩盖问题,但因为上面的简化代码并没有解决它。这是我写的完整课程:
class ConfigFileReader
{
public:
ConfigFileReader() { }
ConfigFileReader(const std::string& config_file_path)
{
setConfigFilePath(config_file_path);
}
~ConfigFileReader() { }
void setConfigFilePath(const std::string& config_file_path)
{
try
{
root_node_ = YAML::LoadFile(config_file_path);
}
catch(const YAML::BadFile& file_load_exception)
{
printf("Error opening YAML file. Maybe the file path is incorrect\n%s", file_load_exception.msg.c_str());
}
}
template<class T>
bool getParam(const std::string& param_key, T& param_value)
{
if (root_node_.IsNull() || !root_node_.IsDefined())
{
printf("Root node is undefined or not set");
return false;
}
YAML::Node node = YAML::Clone(root_node_);
std::vector<std::string> split_name;
boost::split(split_name, param_key, boost::is_any_of("/"));
for(const std::string& str: split_name)
{
if (!node.IsMap())
{
std::cout << "Parameter was not found (Node is null)." << str << std::endl; //replace with printf
return false;
}
node = node[str];
}
if (node.IsNull() || !node.IsDefined())
{
std::cout << "Parameter was not found (Node is null/undefined)." << std::endl;
return false;
}
try
{
param_value = node.as<T>();
return true;
}
catch (const YAML::TypedBadConversion<T>& type_conversion_exception)
{
std::cout << "Error converting param value into specified data type" << std::endl;
std::cout << type_conversion_exception.msg << std::endl;
}
return false;
}
private:
YAML::Node root_node_;
};
然后,在一个单独的cpp文件中是main函数
int main(int argc, char** argv)
{
if (argc != 2)
{
printf("Incorrect number of arguments given");
return EXIT_FAILURE;
}
printf("Config file path: %s", argv[1]);
ConfigFileReader config_file_reader(std::string(argv[1]));
std::string param_out;
bool success = config_file_reader.template getParam<std::string>("controller/filepath", param_out); //<-- ERROR HERE
return EXIT_SUCCESS;
}
编译器: gcc 4.8.4,编译时设置c++11标志。
编辑 2: 在代码中添加了字符串参数构造函数。
【问题讨论】:
-
Cannot reproduce。您是否忘记包含
<string>? -
没有。包含
库。 -
您需要创建一个Minimal, Complete, and Verifiable Example 并展示给我们。
-
template在这里没用。我没有看到带有std::string的ConfigFileReader构造函数。请提供完整的错误信息 -
顺便说一句,如果您不想包含完整示例,因为它涉及到外部库和冗长的代码会掩盖问题,那么您应该阅读minimal reproducible example