我有一个非模板类中的模板功能,像这样的模板函数:错误调用非模板类C++
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文件的主要功能是
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: 添加到代码的字符串参数构造函数。
[无法重现](http://coliru.stacked-crooked.com/a/ece8129982db7ee2)。你忘了包括''? –
Quentin
包含库。 –
Ali250
您需要创建一个[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)并向我们显示。 –