相关疑难解决方法(0)

模板类成员函数的显式特化

我需要为某些类型专门化模板成员函数(比如说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)

我该如何解决这个问题?这里有什么问题?

提前致谢.

c++ gcc templates specialization

81
推荐指数
3
解决办法
7万
查看次数

在B类中声明为朋友的A类成员模板函数无法访问A类的私有成员(仅限Clang)

请查看此代码段.我知道它没有多大意义,它只是为了说明我遇到的问题:

#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)

c++ templates c++11 clang++

16
推荐指数
2
解决办法
590
查看次数

模板类方法的专业化

假设我有以下课程:

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)在这个实例中没有任何意义).

c++ templates

6
推荐指数
1
解决办法
6293
查看次数

标签 统计

c++ ×3

templates ×3

c++11 ×1

clang++ ×1

gcc ×1

specialization ×1