我需要为某些类型专门化模板成员函数(比如说double).它工作正常,而类X本身不是模板类,但是当我创建模板时,GCC开始给出编译时错误.
#include <iostream>
#include <cmath>
template <class C> class X
{
public:
template <class T> void get_as();
};
template <class C>
void X<C>::get_as<double>()
{
}
int main()
{
X<int> x;
x.get_as();
}
Run Code Online (Sandbox Code Playgroud)
这是错误消息
source.cpp:11:27: error: template-id
'get_as<double>' in declaration of primary template
source.cpp:11:6: error: prototype for
'void X<C>::get_as()' does not match any in class 'X<C>'
source.cpp:7:35: error: candidate is:
template<class C> template<class T> void X::get_as()
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?这里有什么问题?
提前致谢.
请查看此代码段.我知道它没有多大意义,它只是为了说明我遇到的问题:
#include <iostream>
using namespace std;
struct tBar
{
template <typename T>
void PrintDataAndAddress(const T& thing)
{
cout << thing.mData;
PrintAddress<T>(thing);
}
private:
// friend struct tFoo; // fixes the compilation error
template <typename T>
void PrintAddress(const T& thing)
{
cout << " - " << &thing << endl;
}
};
struct tFoo
{
friend void tBar::PrintDataAndAddress<tFoo>(const tFoo&);
private:
int mData = 42;
};
struct tWidget
{
int mData = 666;
};
int main()
{
tBar bar;
bar.PrintDataAndAddress(tWidget()); // Fine …Run Code Online (Sandbox Code Playgroud) 假设我有以下课程:
template <typename T>
class MyClass
{
public:
void SetValue(const T &value) { m_value = value; }
private:
T m_value;
};
Run Code Online (Sandbox Code Playgroud)
如何为T = float(或任何其他类型)编写函数的专用版本?
注意:一个简单的重载是不够的,因为我只希望函数可用于T = float(即MyClass :: SetValue(float)在这个实例中没有任何意义).