gpt4 book ai didi

c++ - 与其声明分开定义方法模板

转载 作者:行者123 更新时间:2023-11-28 06:11:07 24 4
gpt4 key购买 nike

以下示例代码无法编译:

#include <iostream>

template<bool Enable>
struct BaseTemplate
{

template< typename Policy>
void templateMethod(Policy& policy);
};


template<bool Enable>
template<typename Policy>
void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
{
std::cout << "template method" << std::endl;
};


int main()
{
BaseTemplate<true> base;
float v = 3.0;
base.templateMethod(v);
};

失败并出现此错误:

$ g++-4.8 -std=c++11 mtempl.cpp -o ./xMtempl
mtempl.cpp:15:65: error: function template partial specialization ‘templateMethod<Policy>’ is not allowed
void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)

现在,这就是让我烦恼的事情:这不是特化,我只是将方法模板与声明分开定义!

如果我更换

template<bool Enable>
template<typename Policy>
void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
{
std::cout << "template method" << std::endl;
};

有了这个

template<bool Enable, typename Policy>
void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
{
std::cout << "template method" << std::endl;
};

我得到的错误是:

mtempl.cpp:16:65: error: template-id ‘templateMethod<Policy>’ in declaration of primary template
void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
^
mtempl.cpp:16:6: error: prototype for ‘void BaseTemplate<Enable>::templateMethod(Policy&)’ does not match any in class ‘BaseTemplate<Enable>’
void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
^
mtempl.cpp:9:7: error: candidate is: template<bool Enable> template<class Policy> void BaseTemplate<Enable>::templateMethod(Policy&)
void templateMethod(Policy& policy);

有什么问题? 如何将方法模板与声明分开定义?

最佳答案

template<bool Enable>
template<typename Policy>
void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
{
// stuff
};

这是特化。删除 <Policy>有一个简单的定义。

template<bool Enable>
template<typename Policy>
void BaseTemplate<Enable>::templateMethod(Policy& policy)
{
// stuff
};

顺便说一句,方法末尾有额外的分号。

关于c++ - 与其声明分开定义方法模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31249730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com